Search in sources :

Example 31 with PrivilegedAction

use of java.security.PrivilegedAction in project ranger by apache.

the class RangerAdminJersey2RESTClient method getServiceTagsIfUpdated.

@Override
public ServiceTags getServiceTagsIfUpdated(final long lastKnownVersion, final long lastActivationTimeInMillis) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerAdminJersey2RESTClient.getServiceTagsIfUpdated(" + lastKnownVersion + ", " + lastActivationTimeInMillis + ")");
    }
    UserGroupInformation user = MiscUtil.getUGILoginUser();
    boolean isSecureMode = user != null && UserGroupInformation.isSecurityEnabled();
    String url = null;
    ServiceTags serviceTags = null;
    Response response = null;
    if (isSecureMode) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Checking Service tags if updated as user : " + user);
        }
        url = _utils.getSecureUrlForTagUpdate(_baseUrl, _serviceName);
        final String secureUrl = url;
        PrivilegedAction<Response> action = new PrivilegedAction<Response>() {

            public Response run() {
                return _client.target(secureUrl).queryParam(RangerRESTUtils.LAST_KNOWN_TAG_VERSION_PARAM, Long.toString(lastKnownVersion)).queryParam(RangerRESTUtils.REST_PARAM_LAST_ACTIVATION_TIME, Long.toString(lastActivationTimeInMillis)).queryParam(RangerRESTUtils.REST_PARAM_PLUGIN_ID, _pluginId).request(MediaType.APPLICATION_JSON_TYPE).get();
            }
        };
        response = user.doAs(action);
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Checking Service tags if updated with old api call");
        }
        url = _utils.getUrlForTagUpdate(_baseUrl, _serviceName);
        response = _client.target(url).queryParam(RangerRESTUtils.LAST_KNOWN_TAG_VERSION_PARAM, Long.toString(lastKnownVersion)).queryParam(RangerRESTUtils.REST_PARAM_LAST_ACTIVATION_TIME, Long.toString(lastActivationTimeInMillis)).queryParam(RangerRESTUtils.REST_PARAM_PLUGIN_ID, _pluginId).request(MediaType.APPLICATION_JSON_TYPE).get();
    }
    int httpResponseCode = response == null ? -1 : response.getStatus();
    String body = null;
    switch(httpResponseCode) {
        case 200:
            body = response.readEntity(String.class);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Response from 200 server: " + body);
            }
            Gson gson = getGson();
            serviceTags = gson.fromJson(body, ServiceTags.class);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Deserialized response to: " + serviceTags);
            }
            break;
        case 304:
            LOG.debug("Got response: 304. Ok. Returning null");
            break;
        case -1:
            LOG.warn("Unexpected: Null response from tag server while trying to get tags! Returning null!");
            break;
        case 404:
            if (response.hasEntity()) {
                body = response.readEntity(String.class);
                if (StringUtils.isNotBlank(body)) {
                    RangerServiceNotFoundException.throwExceptionIfServiceNotFound(_serviceName, body);
                }
            }
            LOG.warn("Received 404 error code with body:[" + body + "], Ignoring");
            break;
        default:
            body = response.readEntity(String.class);
            LOG.warn(String.format("Unexpected: Received status[%d] with body[%s] form url[%s]", httpResponseCode, body, url));
            break;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerAdminJersey2RESTClient.getServiceTagsIfUpdated(" + lastKnownVersion + ", " + lastActivationTimeInMillis + "): " + serviceTags);
    }
    return serviceTags;
}
Also used : Response(javax.ws.rs.core.Response) PrivilegedAction(java.security.PrivilegedAction) Gson(com.google.gson.Gson) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation)

Example 32 with PrivilegedAction

use of java.security.PrivilegedAction in project ranger by apache.

the class RangerAdminRESTClient method getServicePoliciesIfUpdated.

@Override
public ServicePolicies getServicePoliciesIfUpdated(final long lastKnownVersion, final long lastActivationTimeInMillis) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerAdminRESTClient.getServicePoliciesIfUpdated(" + lastKnownVersion + ", " + lastActivationTimeInMillis + ")");
    }
    ServicePolicies ret = null;
    UserGroupInformation user = MiscUtil.getUGILoginUser();
    boolean isSecureMode = user != null && UserGroupInformation.isSecurityEnabled();
    ClientResponse response = null;
    if (isSecureMode) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Checking Service policy if updated as user : " + user);
        }
        PrivilegedAction<ClientResponse> action = new PrivilegedAction<ClientResponse>() {

            public ClientResponse run() {
                WebResource secureWebResource = createWebResource(RangerRESTUtils.REST_URL_POLICY_GET_FOR_SECURE_SERVICE_IF_UPDATED + serviceName).queryParam(RangerRESTUtils.REST_PARAM_LAST_KNOWN_POLICY_VERSION, Long.toString(lastKnownVersion)).queryParam(RangerRESTUtils.REST_PARAM_LAST_ACTIVATION_TIME, Long.toString(lastActivationTimeInMillis)).queryParam(RangerRESTUtils.REST_PARAM_PLUGIN_ID, pluginId).queryParam(RangerRESTUtils.REST_PARAM_CLUSTER_NAME, clusterName);
                return secureWebResource.accept(RangerRESTUtils.REST_MIME_TYPE_JSON).get(ClientResponse.class);
            }
        };
        response = user.doAs(action);
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Checking Service policy if updated with old api call");
        }
        WebResource webResource = createWebResource(RangerRESTUtils.REST_URL_POLICY_GET_FOR_SERVICE_IF_UPDATED + serviceName).queryParam(RangerRESTUtils.REST_PARAM_LAST_KNOWN_POLICY_VERSION, Long.toString(lastKnownVersion)).queryParam(RangerRESTUtils.REST_PARAM_LAST_ACTIVATION_TIME, Long.toString(lastActivationTimeInMillis)).queryParam(RangerRESTUtils.REST_PARAM_PLUGIN_ID, pluginId).queryParam(RangerRESTUtils.REST_PARAM_CLUSTER_NAME, clusterName);
        response = webResource.accept(RangerRESTUtils.REST_MIME_TYPE_JSON).get(ClientResponse.class);
    }
    if (response == null || response.getStatus() == HttpServletResponse.SC_NOT_MODIFIED) {
        if (response == null) {
            LOG.error("Error getting policies; Received NULL response!!. secureMode=" + isSecureMode + ", user=" + user + ", serviceName=" + serviceName);
        } else {
            RESTResponse resp = RESTResponse.fromClientResponse(response);
            if (LOG.isDebugEnabled()) {
                LOG.debug("No change in policies. secureMode=" + isSecureMode + ", user=" + user + ", response=" + resp + ", serviceName=" + serviceName);
            }
        }
        ret = null;
    } else if (response.getStatus() == HttpServletResponse.SC_OK) {
        ret = response.getEntity(ServicePolicies.class);
    } else if (response.getStatus() == HttpServletResponse.SC_NOT_FOUND) {
        LOG.error("Error getting policies; service not found. secureMode=" + isSecureMode + ", user=" + user + ", response=" + response.getStatus() + ", serviceName=" + serviceName + ", " + "lastKnownVersion=" + lastKnownVersion + ", " + "lastActivationTimeInMillis=" + lastActivationTimeInMillis);
        String exceptionMsg = response.hasEntity() ? response.getEntity(String.class) : null;
        RangerServiceNotFoundException.throwExceptionIfServiceNotFound(serviceName, exceptionMsg);
        LOG.warn("Received 404 error code with body:[" + exceptionMsg + "], Ignoring");
    } else {
        RESTResponse resp = RESTResponse.fromClientResponse(response);
        LOG.warn("Error getting policies. secureMode=" + isSecureMode + ", user=" + user + ", response=" + resp + ", serviceName=" + serviceName);
        ret = null;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerAdminRESTClient.getServicePoliciesIfUpdated(" + lastKnownVersion + ", " + lastActivationTimeInMillis + "): " + ret);
    }
    return ret;
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) ServicePolicies(org.apache.ranger.plugin.util.ServicePolicies) PrivilegedAction(java.security.PrivilegedAction) RESTResponse(org.apache.ranger.admin.client.datatype.RESTResponse) WebResource(com.sun.jersey.api.client.WebResource) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation)

Example 33 with PrivilegedAction

use of java.security.PrivilegedAction in project ranger by apache.

the class RangerAdminRESTClient method getServiceTagsIfUpdated.

@Override
public ServiceTags getServiceTagsIfUpdated(final long lastKnownVersion, final long lastActivationTimeInMillis) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerAdminRESTClient.getServiceTagsIfUpdated(" + lastKnownVersion + ", " + lastActivationTimeInMillis + "): ");
    }
    ServiceTags ret = null;
    ClientResponse response = null;
    WebResource webResource = null;
    UserGroupInformation user = MiscUtil.getUGILoginUser();
    boolean isSecureMode = user != null && UserGroupInformation.isSecurityEnabled();
    if (isSecureMode) {
        PrivilegedAction<ClientResponse> action = new PrivilegedAction<ClientResponse>() {

            public ClientResponse run() {
                WebResource secureWebResource = createWebResource(RangerRESTUtils.REST_URL_GET_SECURE_SERVICE_TAGS_IF_UPDATED + serviceName).queryParam(RangerRESTUtils.LAST_KNOWN_TAG_VERSION_PARAM, Long.toString(lastKnownVersion)).queryParam(RangerRESTUtils.REST_PARAM_LAST_ACTIVATION_TIME, Long.toString(lastActivationTimeInMillis)).queryParam(RangerRESTUtils.REST_PARAM_PLUGIN_ID, pluginId);
                return secureWebResource.accept(RangerRESTUtils.REST_MIME_TYPE_JSON).get(ClientResponse.class);
            }
        };
        if (LOG.isDebugEnabled()) {
            LOG.debug("getServiceTagsIfUpdated as user " + user);
        }
        response = user.doAs(action);
    } else {
        webResource = createWebResource(RangerRESTUtils.REST_URL_GET_SERVICE_TAGS_IF_UPDATED + serviceName).queryParam(RangerRESTUtils.LAST_KNOWN_TAG_VERSION_PARAM, Long.toString(lastKnownVersion)).queryParam(RangerRESTUtils.REST_PARAM_LAST_ACTIVATION_TIME, Long.toString(lastActivationTimeInMillis)).queryParam(RangerRESTUtils.REST_PARAM_PLUGIN_ID, pluginId);
        response = webResource.accept(RangerRESTUtils.REST_MIME_TYPE_JSON).get(ClientResponse.class);
    }
    if (response == null || response.getStatus() == HttpServletResponse.SC_NOT_MODIFIED) {
        if (response == null) {
            LOG.error("Error getting tags; Received NULL response!!. secureMode=" + isSecureMode + ", user=" + user + ", serviceName=" + serviceName);
        } else {
            RESTResponse resp = RESTResponse.fromClientResponse(response);
            if (LOG.isDebugEnabled()) {
                LOG.debug("No change in tags. secureMode=" + isSecureMode + ", user=" + user + ", response=" + resp + ", serviceName=" + serviceName + ", " + "lastKnownVersion=" + lastKnownVersion + ", " + "lastActivationTimeInMillis=" + lastActivationTimeInMillis);
            }
        }
        ret = null;
    } else if (response.getStatus() == HttpServletResponse.SC_OK) {
        ret = response.getEntity(ServiceTags.class);
    } else if (response.getStatus() == HttpServletResponse.SC_NOT_FOUND) {
        LOG.error("Error getting tags; service not found. secureMode=" + isSecureMode + ", user=" + user + ", response=" + response.getStatus() + ", serviceName=" + serviceName + ", " + "lastKnownVersion=" + lastKnownVersion + ", " + "lastActivationTimeInMillis=" + lastActivationTimeInMillis);
        String exceptionMsg = response.hasEntity() ? response.getEntity(String.class) : null;
        RangerServiceNotFoundException.throwExceptionIfServiceNotFound(serviceName, exceptionMsg);
        LOG.warn("Received 404 error code with body:[" + exceptionMsg + "], Ignoring");
    } else {
        RESTResponse resp = RESTResponse.fromClientResponse(response);
        LOG.warn("Error getting tags. secureMode=" + isSecureMode + ", user=" + user + ", response=" + resp + ", serviceName=" + serviceName);
        ret = null;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerAdminRESTClient.getServiceTagsIfUpdated(" + lastKnownVersion + ", " + lastActivationTimeInMillis + "): ");
    }
    return ret;
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) PrivilegedAction(java.security.PrivilegedAction) RESTResponse(org.apache.ranger.admin.client.datatype.RESTResponse) ServiceTags(org.apache.ranger.plugin.util.ServiceTags) WebResource(com.sun.jersey.api.client.WebResource) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation)

Example 34 with PrivilegedAction

use of java.security.PrivilegedAction in project felix by apache.

the class EventDispatcher method invokeServiceListenerCallback.

private static void invokeServiceListenerCallback(Bundle bundle, final EventListener l, Filter filter, Object acc, final EventObject event, final Dictionary oldProps) {
    // STOPPING, and ACTIVE bundles.
    if ((bundle.getState() != Bundle.STARTING) && (bundle.getState() != Bundle.STOPPING) && (bundle.getState() != Bundle.ACTIVE)) {
        return;
    }
    // Check that the bundle has permission to get at least
    // one of the service interfaces; the objectClass property
    // of the service stores its service interfaces.
    ServiceReference ref = ((ServiceEvent) event).getServiceReference();
    boolean hasPermission = true;
    Object sm = System.getSecurityManager();
    if ((acc != null) && (sm != null)) {
        try {
            ServicePermission perm = new ServicePermission(ref, ServicePermission.GET);
            ((SecurityManager) sm).checkPermission(perm, acc);
        } catch (Exception ex) {
            hasPermission = false;
        }
    }
    if (hasPermission) {
        // Dispatch according to the filter.
        boolean matched;
        if (l instanceof UnfilteredServiceListener) {
            // An UnfilteredServiceListener always matches, regardless of the filter.
            // The filter is still passed on to the Service Registry Hooks.
            matched = true;
        } else {
            matched = (filter == null) || filter.match(((ServiceEvent) event).getServiceReference());
        }
        if (matched) {
            if ((l instanceof AllServiceListener) || Util.isServiceAssignable(bundle, ((ServiceEvent) event).getServiceReference())) {
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(new PrivilegedAction() {

                        @Override
                        public Object run() {
                            ((ServiceListener) l).serviceChanged((ServiceEvent) event);
                            return null;
                        }
                    });
                } else {
                    ((ServiceListener) l).serviceChanged((ServiceEvent) event);
                }
            }
        } else // matched previously.
        if (((ServiceEvent) event).getType() == ServiceEvent.MODIFIED) {
            if (filter.match(oldProps)) {
                final ServiceEvent se = new ServiceEvent(ServiceEvent.MODIFIED_ENDMATCH, ((ServiceEvent) event).getServiceReference());
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(new PrivilegedAction() {

                        @Override
                        public Object run() {
                            ((ServiceListener) l).serviceChanged(se);
                            return null;
                        }
                    });
                } else {
                    ((ServiceListener) l).serviceChanged(se);
                }
            }
        }
    }
}
Also used : AllServiceListener(org.osgi.framework.AllServiceListener) UnfilteredServiceListener(org.osgi.framework.UnfilteredServiceListener) ServiceListener(org.osgi.framework.ServiceListener) PrivilegedAction(java.security.PrivilegedAction) ServiceEvent(org.osgi.framework.ServiceEvent) ServicePermission(org.osgi.framework.ServicePermission) EventObject(java.util.EventObject) ServiceReference(org.osgi.framework.ServiceReference) UnfilteredServiceListener(org.osgi.framework.UnfilteredServiceListener) AllServiceListener(org.osgi.framework.AllServiceListener)

Example 35 with PrivilegedAction

use of java.security.PrivilegedAction in project felix by apache.

the class MX4JMBeanServer method createClassLoaderRepository.

/**
 * Creates a new ClassLoaderRepository for ClassLoader MBeans.
 * The system property {@link mx4j.MX4JSystemKeys#MX4J_MBEANSERVER_CLASSLOADER_REPOSITORY}
 * is tested for a full qualified name of a class
 * extending the {@link ModifiableClassLoaderRepository} class.
 * In case the system property is not defined or the class is not loadable or instantiable, a default
 * implementation is returned.
 */
private ModifiableClassLoaderRepository createClassLoaderRepository() {
    Logger logger = getLogger();
    if (logger.isEnabledFor(Logger.TRACE))
        logger.trace("Checking for system property " + MX4JSystemKeys.MX4J_MBEANSERVER_CLASSLOADER_REPOSITORY);
    String value = (String) AccessController.doPrivileged(new PrivilegedAction() {

        public Object run() {
            return System.getProperty(MX4JSystemKeys.MX4J_MBEANSERVER_CLASSLOADER_REPOSITORY);
        }
    });
    if (value != null) {
        if (logger.isEnabledFor(Logger.DEBUG))
            logger.debug("Property found for custom ClassLoaderRepository; class is: " + value);
        try {
            ModifiableClassLoaderRepository repository = (ModifiableClassLoaderRepository) Thread.currentThread().getContextClassLoader().loadClass(value).newInstance();
            if (logger.isEnabledFor(Logger.TRACE))
                logger.trace("Custom ClassLoaderRepository created successfully " + repository);
            return repository;
        } catch (Exception x) {
            if (logger.isEnabledFor(Logger.TRACE))
                logger.trace("Custom ClassLoaderRepository could not be created", x);
        }
    }
    return new DefaultClassLoaderRepository();
}
Also used : PrivilegedAction(java.security.PrivilegedAction) Logger(org.apache.felix.mosgi.jmx.agent.mx4j.log.Logger) IntrospectionException(javax.management.IntrospectionException) OperationsException(javax.management.OperationsException) BadBinaryOpValueExpException(javax.management.BadBinaryOpValueExpException) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) BadStringOperationException(javax.management.BadStringOperationException) ReflectionException(javax.management.ReflectionException) NotCompliantMBeanException(javax.management.NotCompliantMBeanException) RuntimeErrorException(javax.management.RuntimeErrorException) MalformedObjectNameException(javax.management.MalformedObjectNameException) ListenerNotFoundException(javax.management.ListenerNotFoundException) RuntimeOperationsException(javax.management.RuntimeOperationsException) AttributeNotFoundException(javax.management.AttributeNotFoundException) MBeanRegistrationException(javax.management.MBeanRegistrationException) InstanceNotFoundException(javax.management.InstanceNotFoundException) JMRuntimeException(javax.management.JMRuntimeException) PrivilegedActionException(java.security.PrivilegedActionException) BadAttributeValueExpException(javax.management.BadAttributeValueExpException) IOException(java.io.IOException) ImplementationException(org.apache.felix.mosgi.jmx.agent.mx4j.ImplementationException) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) MBeanException(javax.management.MBeanException) InvalidApplicationException(javax.management.InvalidApplicationException)

Aggregations

PrivilegedAction (java.security.PrivilegedAction)359 IOException (java.io.IOException)85 Subject (javax.security.auth.Subject)61 AccessControlContext (java.security.AccessControlContext)31 File (java.io.File)29 HashMap (java.util.HashMap)29 UserGroupInformation (org.apache.hadoop.security.UserGroupInformation)29 Method (java.lang.reflect.Method)24 ArrayList (java.util.ArrayList)23 ClientResponse (com.sun.jersey.api.client.ClientResponse)21 InputStream (java.io.InputStream)21 URL (java.net.URL)21 FileNotFoundException (java.io.FileNotFoundException)18 UnsupportedEncodingException (java.io.UnsupportedEncodingException)18 Iterator (java.util.Iterator)18 MalformedURLException (java.net.MalformedURLException)17 List (java.util.List)17 UnknownHostException (java.net.UnknownHostException)16 Principal (java.security.Principal)15 PrivilegedActionException (java.security.PrivilegedActionException)15