org.apache.ranger.plugin.service.RangerBasePlugin Java Examples

The following examples show how to use org.apache.ranger.plugin.service.RangerBasePlugin. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RangerDefaultAuditHandler.java    From ranger with Apache License 2.0 6 votes vote down vote up
public void logAuthzAudit(AuthzAuditEvent auditEvent) {
	if(LOG.isDebugEnabled()) {
		LOG.debug("==> RangerDefaultAuditHandler.logAuthzAudit(" + auditEvent + ")");
	}

	if(auditEvent != null) {
		populateDefaults(auditEvent);

		AuditHandler auditProvider = RangerBasePlugin.getAuditProvider(auditEvent.getRepositoryName());
		if (auditProvider == null || !auditProvider.log(auditEvent)) {
			MiscUtil.logErrorMessageByInterval(LOG, "fail to log audit event " + auditEvent);
		}
	}

	if(LOG.isDebugEnabled()) {
		LOG.debug("<== RangerDefaultAuditHandler.logAuthzAudit(" + auditEvent + ")");
	}
}
 
Example #2
Source File: RangerGaianAuthorizer.java    From egeria with Apache License 2.0 6 votes vote down vote up
public void init() {
    logger.logDetail("==> RangerGaianPlugin.init()");
    RangerBasePlugin plugin = gaianPlugin;

    if (plugin == null) {
        synchronized (RangerGaianPlugin.class) {
            plugin = gaianPlugin;

            if (plugin == null) {
                plugin = new RangerGaianPlugin();
                plugin.init();
                plugin.setResultProcessor(new RangerDefaultAuditHandler());
                gaianPlugin = plugin;
            }
        }
    }
    logger.logDetail("<== RangerGaianPlugin.init()");
}
 
Example #3
Source File: RangerOzoneAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
public RangerOzoneAuthorizer() {
	rangerPlugin = new RangerBasePlugin("ozone", "ozone");

	rangerPlugin.init(); // this will initialize policy engine and policy refresher
	auditHandler = new RangerDefaultAuditHandler();
	rangerPlugin.setResultProcessor(auditHandler);
}
 
Example #4
Source File: AuthorizationSessionTest.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthorize() {
	RangerBasePlugin plugin = new RangerBasePlugin("hbase", "hbase");
	
	User user = mock(User.class);
	when(user.getShortName()).thenReturn("user1");
	when(user.getGroupNames()).thenReturn(new String[] { "users" } );
	AuthorizationSession session = new AuthorizationSession(plugin);
	session.access("read")
		.user(user)
		.table(":meta:")
		.buildRequest()
		.authorize();
}
 
Example #5
Source File: TestPolicyEngine.java    From ranger with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
	plugin = new RangerBasePlugin("hbase", "hbase");
	gsonBuilder = new GsonBuilder().setDateFormat("yyyyMMdd-HH:mm:ss.SSS-Z")
								   .setPrettyPrinting()
								   .registerTypeAdapter(RangerAccessRequest.class, new RangerAccessRequestDeserializer())
								   .registerTypeAdapter(RangerAccessResource.class,  new RangerResourceDeserializer())
								   .create();
}
 
Example #6
Source File: TestRangerAuthContext.java    From ranger with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
	gsonBuilder = new GsonBuilder().setDateFormat("yyyyMMdd-HH:mm:ss.SSS-Z")
			.setPrettyPrinting()
			.create();

	plugin = new RangerBasePlugin("hive", "TestRangerAuthContext");
}
 
Example #7
Source File: PolicyRefresher.java    From ranger with Apache License 2.0 5 votes vote down vote up
public PolicyRefresher(RangerBasePlugin plugIn) {
	if(LOG.isDebugEnabled()) {
		LOG.debug("==> PolicyRefresher(serviceName=" + plugIn.getServiceName() + ").PolicyRefresher()");
	}

	RangerPluginConfig pluginConfig   = plugIn.getConfig();
	String             propertyPrefix = pluginConfig.getPropertyPrefix();

	this.plugIn      = plugIn;
	this.serviceType = plugIn.getServiceType();
	this.serviceName = plugIn.getServiceName();
	this.cacheDir    = pluginConfig.get(propertyPrefix + ".policy.cache.dir");

	String appId         = StringUtils.isEmpty(plugIn.getAppId()) ? serviceType : plugIn.getAppId();
	String cacheFilename = String.format("%s_%s.json", appId, serviceName);

	cacheFilename = cacheFilename.replace(File.separatorChar,  '_');
	cacheFilename = cacheFilename.replace(File.pathSeparatorChar,  '_');

	this.cacheFileName = cacheFilename;

	Gson gson = null;
	try {
		gson = new GsonBuilder().setDateFormat("yyyyMMdd-HH:mm:ss.SSS-Z").create();
	} catch(Throwable excp) {
		LOG.fatal("PolicyRefresher(): failed to create GsonBuilder object", excp);
	}

	this.gson                          = gson;
	this.disableCacheIfServiceNotFound = pluginConfig.getBoolean(propertyPrefix + ".disable.cache.if.servicenotfound", true);
	this.rangerAdmin                   = RangerBasePlugin.createAdminClient(pluginConfig);
	this.rolesProvider                 = new RangerRolesProvider(getServiceType(), appId, getServiceName(), rangerAdmin,  cacheDir, pluginConfig);
	this.pollingIntervalMs             = pluginConfig.getLong(propertyPrefix + ".policy.pollIntervalMs", 30 * 1000);

	setName("PolicyRefresher(serviceName=" + serviceName + ")-" + getId());

	if(LOG.isDebugEnabled()) {
		LOG.debug("<== PolicyRefresher(serviceName=" + serviceName + ").PolicyRefresher()");
	}
}
 
Example #8
Source File: RangerAdminUserStoreRetriever.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Map<String, String> options) {

    if (StringUtils.isNotBlank(serviceName) && serviceDef != null && StringUtils.isNotBlank(appId)) {
        RangerPluginConfig pluginConfig = super.pluginConfig;

        if (pluginConfig == null) {
            pluginConfig = new RangerPluginConfig(serviceDef.getName(), serviceName, appId, null, null, null);
        }

        adminClient = RangerBasePlugin.createAdminClient(pluginConfig);
    } else {
        LOG.error("FATAL: Cannot find service/serviceDef to use for retrieving userstore. Will NOT be able to retrieve userstore.");
    }
}
 
Example #9
Source File: RangerAdminTagRetriever.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Map<String, String> options) {

	if (StringUtils.isNotBlank(serviceName) && serviceDef != null && StringUtils.isNotBlank(appId)) {
		RangerPluginConfig pluginConfig = super.pluginConfig;

		if (pluginConfig == null) {
			pluginConfig = new RangerPluginConfig(serviceDef.getName(), serviceName, appId, null, null, null);
		}

		adminClient = RangerBasePlugin.createAdminClient(pluginConfig);
	} else {
		LOG.error("FATAL: Cannot find service/serviceDef to use for retrieving tags. Will NOT be able to retrieve tags.");
	}
}
 
Example #10
Source File: RangerAtlasAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
private boolean checkAccess(RangerAccessRequestImpl request, RangerAtlasAuditHandler auditHandler) {
    boolean          ret    = false;
    RangerBasePlugin plugin = atlasPlugin;

    if (plugin != null) {
        RangerAccessResult result = plugin.isAccessAllowed(request, auditHandler);

        ret = result != null && result.getIsAllowed();
    } else {
        LOG.warn("RangerAtlasPlugin not initialized. Access blocked!!!");
    }

    return ret;
}
 
Example #11
Source File: RangerAtlasAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
private boolean checkAccess(RangerAccessRequestImpl request) {
    boolean          ret    = false;
    RangerBasePlugin plugin = atlasPlugin;

    if (plugin != null) {
        RangerAccessResult result = plugin.isAccessAllowed(request);

        ret = result != null && result.getIsAllowed();
    } else {
        LOG.warn("RangerAtlasPlugin not initialized. Access blocked!!!");
    }

    return ret;
}
 
Example #12
Source File: RangerAtlasAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public void init() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerAtlasPlugin.init()");
    }

    RangerBasePlugin plugin = atlasPlugin;

    if (plugin == null) {
        synchronized (RangerAtlasPlugin.class) {
            plugin = atlasPlugin;

            if (plugin == null) {
                plugin = new RangerAtlasPlugin();

                plugin.init();

                plugin.setResultProcessor(new RangerDefaultAuditHandler(plugin.getConfig()));

                atlasPlugin = plugin;
            }
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerAtlasPlugin.init()");
    }
}
 
Example #13
Source File: RangerKafkaAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(Map<String, ?> configs) {
	RangerBasePlugin me = rangerPlugin;
	if (me == null) {
		synchronized(RangerKafkaAuthorizer.class) {
			me = rangerPlugin;
			if (me == null) {
				try {
					// Possible to override JAAS configuration which is used by Ranger, otherwise
					// SASL_PLAINTEXT is used, which force Kafka to use 'sasl_plaintext.KafkaServer',
					// if it's not defined, then it reverts to 'KafkaServer' configuration.
					final Object jaasContext = configs.get("ranger.jaas.context");
					final String listenerName = (jaasContext instanceof String
							&& StringUtils.isNotEmpty((String) jaasContext)) ? (String) jaasContext
									: SecurityProtocol.SASL_PLAINTEXT.name();
					final String saslMechanism = SaslConfigs.GSSAPI_MECHANISM;
					JaasContext context = JaasContext.loadServerContext(new ListenerName(listenerName), saslMechanism, configs);
					LoginManager loginManager = LoginManager.acquireLoginManager(context, saslMechanism, KerberosLogin.class, configs);
					Subject subject = loginManager.subject();
					UserGroupInformation ugi = MiscUtil
							.createUGIFromSubject(subject);
					if (ugi != null) {
						MiscUtil.setUGILoginUser(ugi, subject);
					}
					logger.info("LoginUser=" + MiscUtil.getUGILoginUser());
				} catch (Throwable t) {
					logger.error("Error getting principal.", t);
				}
				me = rangerPlugin = new RangerBasePlugin("kafka", "kafka");
			}
		}
	}
	logger.info("Calling plugin.init()");
	rangerPlugin.init();
	auditHandler = new RangerKafkaAuditHandler();
	rangerPlugin.setResultProcessor(auditHandler);
}
 
Example #14
Source File: RangerHivePolicyProvider.java    From ranger with Apache License 2.0 5 votes vote down vote up
public RangerHivePolicyProvider(@NotNull RangerBasePlugin hivePlugin) {

		Set<String> privileges = new HashSet<>();
		for (HiveResourceACLs.Privilege privilege : HiveResourceACLs.Privilege.values()) {
			privileges.add(privilege.name().toLowerCase());
		}

		this.hivePrivileges = new HashSet<>(privileges);
		this.rangerPlugin   = hivePlugin;
	}
 
Example #15
Source File: RangerAtlasAuthorizer.java    From ranger with Apache License 2.0 4 votes vote down vote up
private RangerServiceDef getServiceDef() {
    RangerBasePlugin plugin = atlasPlugin;

    return plugin != null ? plugin.getServiceDef() : null;
}
 
Example #16
Source File: PolicyRefresher.java    From ranger with Apache License 2.0 4 votes vote down vote up
/**
 * @return the plugIn
 */
public RangerBasePlugin getPlugin() {
	return plugIn;
}
 
Example #17
Source File: AuthorizationSession.java    From ranger with Apache License 2.0 4 votes vote down vote up
public AuthorizationSession(RangerBasePlugin authorizer) {
	_authorizer = authorizer;
}
 
Example #18
Source File: RangerPluginPerfTester.java    From ranger with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {

		if (!parseArguments(args)) {
			System.err.println("Exiting.. ");
			System.exit(-1);
		}



		System.out.println("Arguments:");
		System.out.println("\t\tservice-type:\t\t\t" + serviceType);
		System.out.println("\t\tservice-name:\t\t\t" + serviceName);
		System.out.println("\t\tapp-id:\t\t\t\t" + appId);
		System.out.println("\t\tranger-host:\t\t\t" + rangerHostName);
		System.out.println("\t\tsocket-read-timeout:\t\t" + socketReadTimeout);
		System.out.println("\t\tpolling-interval:\t\t" + pollingInterval);
		System.out.println("\t\tpolicy-cache-dir:\t\t" + policyCacheDir);
		System.out.println("\t\tuse-cached-policy-evaluator:\t" + useCachedPolicyEvaluator);
		System.out.println("\n\n");


		Path filePath = buildConfigurationFile();

		if (filePath != null) {
			plugin = new RangerBasePlugin(serviceType, appId);

			plugin.getConfig().addResource(filePath);

			Runtime runtime = Runtime.getRuntime();
			runtime.gc();

			long totalMemory = runtime.totalMemory();
			long freeMemory = runtime.freeMemory();

			System.out.println("Initial Memory Statistics:");
			System.out.println("\t\tMaximum Memory available for the process:\t" + runtime.maxMemory());
			System.out.println("\t\tInitial In-Use memory:\t\t\t\t" + (totalMemory-freeMemory));
			System.out.println("\t\tInitial Free memory:\t\t\t\t" + freeMemory);

			System.out.println("\n\n");

			plugin.init();

			while (true) {

				runtime.gc();

				freeMemory = runtime.freeMemory();
				totalMemory = runtime.totalMemory();

				System.out.println("Memory Statistics:");
				System.out.println("\t\tCurrently In-Use memory:\t" + (totalMemory-freeMemory));
				System.out.println("\t\tCurrently Free memory:\t\t" + freeMemory);

				System.out.println("\n\n");

				try {
					Thread.sleep(60 * 1000);
				} catch (InterruptedException e) {

					System.err.println("Main thread interrupted..., exiting...");
					break;
				}
			}
		} else {
			System.err.println("Failed to build configuration file");
		}
	}
 
Example #19
Source File: RangerSolrAuthorizer.java    From ranger with Apache License 2.0 4 votes vote down vote up
@Override
public void init(Map<String, Object> initInfo) {
	logger.info("init()");

	try {
		RangerBasePlugin me = solrPlugin;
		if (me == null) {
			synchronized(RangerSolrAuthorizer.class) {
				me = solrPlugin;
				logger.info("RangerSolrAuthorizer(): init called");
				if (me == null) {
					authToJAASFile();
					logger.info("Creating RangerSolrPlugin");
					me = solrPlugin = new RangerBasePlugin("solr", "solr");
				}
			}
		}
		logger.info("Calling solrPlugin.init()");
		solrPlugin.init();
		auditHandler = new RangerSolrAuditHandler(solrPlugin.getConfig());
		solrPlugin.setResultProcessor(auditHandler);
		useProxyIP = solrPlugin.getConfig().getBoolean(
				PROP_USE_PROXY_IP, useProxyIP);
		proxyIPHeader = solrPlugin.getConfig().get(
				PROP_PROXY_IP_HEADER, proxyIPHeader);
		// First get from the -D property
		solrAppName = System.getProperty("solr.kerberos.jaas.appname",
				solrAppName);
		// Override if required from Ranger properties
		solrAppName = solrPlugin.getConfig().get(
				PROP_SOLR_APP_NAME, solrAppName);

		logger.info("init(): useProxyIP=" + useProxyIP);
		logger.info("init(): proxyIPHeader=" + proxyIPHeader);
		logger.info("init(): solrAppName=" + solrAppName);
		logger.info("init(): KerberosName.rules="
				+ MiscUtil.getKerberosNamesRules());
	} catch (Throwable t) {
		logger.fatal("Error creating and initializing RangerBasePlugin()");
	}
}