Common library for Apache Ranger plugins providing shared functionality, models, and utilities for security policy enforcement across various big data components.
—
Kerberos authentication support and security utilities for secure communication and credential management. This module provides comprehensive security infrastructure including Kerberos integration, secure client login mechanisms, credential management, and authentication context handling for enterprise security environments.
Core utility class providing Kerberos authentication and secure login functionality for Ranger components.
/**
* Utility class for secure client authentication using Kerberos
*/
public class SecureClientLogin {
/**
* Hostname placeholder for principal names that gets replaced with actual hostname
*/
public static final String HOSTNAME_PATTERN = "_HOST";
/**
* Login user from keytab file using Kerberos authentication
* @param user - Principal name (may contain _HOST placeholder)
* @param path - Path to keytab file
* @return Subject with Kerberos credentials
* @throws IOException if login fails or keytab is invalid
*/
public static Subject loginUserFromKeytab(String user, String path) throws IOException;
/**
* Login user from keytab file with custom name rules
* @param user - Principal name (may contain _HOST placeholder)
* @param path - Path to keytab file
* @param nameRules - Custom Kerberos name rules for principal mapping
* @return Subject with Kerberos credentials
* @throws IOException if login fails or keytab is invalid
*/
public static Subject loginUserFromKeytab(String user, String path, String nameRules) throws IOException;
/**
* Login user with username and password
* @param user - Username for authentication
* @param password - Password for authentication
* @return Subject with authentication credentials
* @throws IOException if authentication fails
*/
public static Subject loginUserWithPassword(String user, String password) throws IOException;
/**
* Login using current user context (from system properties or environment)
* @param user - Username to login as
* @return Subject with current user credentials
* @throws IOException if login fails
*/
public static Subject login(String user) throws IOException;
/**
* Get user principals from an authenticated subject
* @param subject - Authenticated subject
* @return Set of user principals
*/
public static Set<Principal> getUserPrincipals(Subject subject);
/**
* Create a user principal for the given login name
* @param loginName - Login name to create principal for
* @return User principal object
*/
public static Principal createUserPrincipal(String loginName);
/**
* Check if Kerberos credentials exist for the specified principal and keytab
* @param principal - Kerberos principal name
* @param keytabPath - Path to keytab file
* @return True if valid Kerberos credentials exist
*/
public static boolean isKerberosCredentialExists(String principal, String keytabPath);
/**
* Get the actual principal name by replacing _HOST with actual hostname
* @param principalConfig - Principal configuration (may contain _HOST)
* @param hostName - Hostname to substitute for _HOST
* @return Resolved principal name
* @throws IOException if hostname resolution fails
*/
public static String getPrincipal(String principalConfig, String hostName) throws IOException;
/**
* Get the current hostname for principal name resolution
* @return Current hostname
* @throws IOException if hostname cannot be determined
*/
public static String getHostname() throws IOException;
/**
* Validate keytab file and principal combination
* @param principal - Kerberos principal
* @param keytabPath - Path to keytab file
* @return True if keytab contains valid credentials for principal
*/
public static boolean validateKeytab(String principal, String keytabPath);
/**
* Refresh Kerberos credentials for a subject
* @param subject - Subject to refresh credentials for
* @return Refreshed subject with new credentials
* @throws IOException if credential refresh fails
*/
public static Subject refreshCredentials(Subject subject) throws IOException;
}Custom Kerberos login module that securely handles password-based authentication while integrating with the Java security framework.
/**
* Custom Kerberos login module for password-based authentication
* Implements the standard JAAS LoginModule interface
*/
public class KrbPasswordSaverLoginModule implements LoginModule {
/**
* Configuration parameter name for username
*/
public static final String USERNAME_PARAM = "javax.security.auth.login.name";
/**
* Configuration parameter name for password
*/
public static final String PASSWORD_PARAM = "javax.security.auth.login.password";
/**
* Configuration parameter for debug mode
*/
public static final String DEBUG_PARAM = "debug";
/**
* Configuration parameter for storing password in shared state
*/
public static final String STORE_PASSWORD_PARAM = "storePassword";
/**
* Configuration parameter for clearing password after use
*/
public static final String CLEAR_PASS_PARAM = "clearPass";
/**
* Default constructor for login module
*/
public KrbPasswordSaverLoginModule();
/**
* Initialize the login module
* @param subject - Subject to be authenticated
* @param callbackhandler - Handler for authentication callbacks
* @param sharedMap - Shared state between login modules
* @param options - Configuration options for this login module
*/
public void initialize(Subject subject, CallbackHandler callbackhandler,
Map<String, ?> sharedMap, Map<String, ?> options);
/**
* Perform the authentication login
* @return True if authentication succeeds
* @throws LoginException if authentication fails
*/
public boolean login() throws LoginException;
/**
* Commit the authentication (add principals and credentials to subject)
* @return True if commit succeeds
* @throws LoginException if commit fails
*/
public boolean commit() throws LoginException;
/**
* Abort the authentication process
* @return True if abort succeeds
* @throws LoginException if abort fails
*/
public boolean abort() throws LoginException;
/**
* Logout and remove principals/credentials from subject
* @return True if logout succeeds
* @throws LoginException if logout fails
*/
public boolean logout() throws LoginException;
/**
* Check if debug mode is enabled
* @return True if debug logging is enabled
*/
public boolean isDebugEnabled();
/**
* Get the authenticated username
* @return Username from authentication
*/
public String getUsername();
/**
* Clear stored password from memory
*/
public void clearPassword();
}Classes for managing authentication context and credentials in multi-threaded environments.
/**
* Authentication context manager for thread-safe credential handling
*/
public class RangerAuthenticationContext {
/**
* Set authentication context for current thread
* @param subject - Authenticated subject
*/
public static void setCurrentSubject(Subject subject);
/**
* Get authentication context for current thread
* @return Current authenticated subject or null
*/
public static Subject getCurrentSubject();
/**
* Clear authentication context for current thread
*/
public static void clearCurrentSubject();
/**
* Execute privileged action with authenticated subject
* @param action - Action to execute
* @param subject - Subject to use for execution
* @return Result of privileged action
* @throws Exception if action execution fails
*/
public static <T> T doAsPrivileged(PrivilegedExceptionAction<T> action, Subject subject) throws Exception;
/**
* Check if current thread has valid authentication context
* @return True if authenticated context exists
*/
public static boolean isAuthenticated();
/**
* Get current user principal name
* @return Principal name or null if not authenticated
*/
public static String getCurrentUserName();
/**
* Get current user's group memberships
* @return Set of group names
*/
public static Set<String> getCurrentUserGroups();
}
/**
* Credential manager for secure handling of authentication credentials
*/
public class RangerCredentialManager {
/**
* Store credentials securely in memory
* @param alias - Credential alias/identifier
* @param credential - Credential to store
*/
public void storeCredential(String alias, char[] credential);
/**
* Retrieve stored credentials
* @param alias - Credential alias/identifier
* @return Stored credential or null if not found
*/
public char[] getCredential(String alias);
/**
* Remove credentials from secure storage
* @param alias - Credential alias/identifier
* @return True if credential was removed
*/
public boolean removeCredential(String alias);
/**
* Clear all stored credentials
*/
public void clearAllCredentials();
/**
* Check if credential exists
* @param alias - Credential alias/identifier
* @return True if credential is stored
*/
public boolean hasCredential(String alias);
/**
* Get list of stored credential aliases
* @return Set of credential aliases
*/
public Set<String> getCredentialAliases();
}
/**
* Security utilities for Ranger components
*/
public class RangerSecurityUtils {
/**
* Encrypt sensitive data using configured encryption
* @param data - Data to encrypt
* @param key - Encryption key
* @return Encrypted data
*/
public static byte[] encrypt(byte[] data, String key);
/**
* Decrypt sensitive data using configured decryption
* @param encryptedData - Data to decrypt
* @param key - Decryption key
* @return Decrypted data
*/
public static byte[] decrypt(byte[] encryptedData, String key);
/**
* Generate secure random password
* @param length - Password length
* @return Generated password
*/
public static char[] generateSecurePassword(int length);
/**
* Hash password using secure hashing algorithm
* @param password - Password to hash
* @param salt - Salt for hashing
* @return Hashed password
*/
public static String hashPassword(char[] password, byte[] salt);
/**
* Verify password against hash
* @param password - Password to verify
* @param hash - Hash to verify against
* @param salt - Salt used for hashing
* @return True if password matches hash
*/
public static boolean verifyPassword(char[] password, String hash, byte[] salt);
/**
* Generate cryptographic salt
* @return Random salt bytes
*/
public static byte[] generateSalt();
}Classes for configuring SSL/TLS security for Ranger communications.
/**
* SSL configuration and utilities for secure communications
*/
public class RangerSSLConfig {
/**
* Configuration key for SSL enabled flag
*/
public static final String SSL_ENABLED = "ranger.ssl.enabled";
/**
* Configuration key for keystore path
*/
public static final String KEYSTORE_PATH = "ranger.ssl.keystore.file";
/**
* Configuration key for keystore password
*/
public static final String KEYSTORE_PASSWORD = "ranger.ssl.keystore.password";
/**
* Configuration key for truststore path
*/
public static final String TRUSTSTORE_PATH = "ranger.ssl.truststore.file";
/**
* Configuration key for truststore password
*/
public static final String TRUSTSTORE_PASSWORD = "ranger.ssl.truststore.password";
/**
* Initialize SSL configuration from properties
* @param config - Configuration properties
*/
public void init(Configuration config);
/**
* Check if SSL is enabled
* @return True if SSL is enabled
*/
public boolean isSSLEnabled();
/**
* Get SSL context for secure communications
* @return Configured SSL context
* @throws Exception if SSL context creation fails
*/
public SSLContext getSSLContext() throws Exception;
/**
* Create SSL socket factory
* @return SSL socket factory
* @throws Exception if factory creation fails
*/
public SSLSocketFactory createSSLSocketFactory() throws Exception;
/**
* Create trust manager for certificate validation
* @return Array of trust managers
* @throws Exception if trust manager creation fails
*/
public TrustManager[] createTrustManagers() throws Exception;
/**
* Create key manager for client certificates
* @return Array of key managers
* @throws Exception if key manager creation fails
*/
public KeyManager[] createKeyManagers() throws Exception;
/**
* Validate SSL configuration
* @return True if configuration is valid
*/
public boolean validateConfiguration();
}Usage Examples:
import org.apache.hadoop.security.SecureClientLogin;
import org.apache.hadoop.security.KrbPasswordSaverLoginModule;
import javax.security.auth.Subject;
import java.security.PrivilegedExceptionAction;
// Kerberos authentication with keytab
public class KerberosAuthenticationExample {
public void authenticateWithKeytab() {
try {
// Define Kerberos principal and keytab path
String principal = "ranger/hostname@EXAMPLE.COM";
String keytabPath = "/etc/security/keytabs/ranger.keytab";
// Check if credentials exist before attempting login
if (!SecureClientLogin.isKerberosCredentialExists(principal, keytabPath)) {
throw new IOException("Kerberos credentials not found for " + principal);
}
// Resolve hostname in principal if needed
String resolvedPrincipal = SecureClientLogin.getPrincipal(
"ranger/_HOST@EXAMPLE.COM",
SecureClientLogin.getHostname()
);
// Perform keytab-based login
Subject subject = SecureClientLogin.loginUserFromKeytab(resolvedPrincipal, keytabPath);
// Set authentication context
RangerAuthenticationContext.setCurrentSubject(subject);
// Execute privileged operations
String result = RangerAuthenticationContext.doAsPrivileged(
new PrivilegedExceptionAction<String>() {
@Override
public String run() throws Exception {
// Perform authenticated operations here
return "Authenticated operation completed";
}
},
subject
);
System.out.println("Operation result: " + result);
// Get authentication info
Set<Principal> principals = SecureClientLogin.getUserPrincipals(subject);
for (Principal p : principals) {
System.out.println("Authenticated as: " + p.getName());
}
} catch (IOException e) {
System.err.println("Kerberos authentication failed: " + e.getMessage());
} finally {
// Clear authentication context
RangerAuthenticationContext.clearCurrentSubject();
}
}
}
// Password-based authentication using JAAS
public class PasswordAuthenticationExample {
public void authenticateWithPassword() {
try {
// Configure JAAS login context
Configuration jaasConfig = new Configuration() {
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
Map<String, String> options = new HashMap<>();
options.put("debug", "true");
options.put("storePassword", "true");
options.put("clearPass", "false");
return new AppConfigurationEntry[] {
new AppConfigurationEntry(
"org.apache.hadoop.security.KrbPasswordSaverLoginModule",
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
options
)
};
}
};
Configuration.setConfiguration(jaasConfig);
// Create login context
LoginContext loginContext = new LoginContext("RangerAuth", new CallbackHandler() {
@Override
public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
((NameCallback) callback).setName("alice@EXAMPLE.COM");
} else if (callback instanceof PasswordCallback) {
((PasswordCallback) callback).setPassword("password123".toCharArray());
}
}
}
});
// Perform login
loginContext.login();
Subject subject = loginContext.getSubject();
// Use authenticated subject
RangerAuthenticationContext.setCurrentSubject(subject);
System.out.println("Password authentication successful");
System.out.println("Current user: " + RangerAuthenticationContext.getCurrentUserName());
} catch (LoginException e) {
System.err.println("Password authentication failed: " + e.getMessage());
}
}
}
// Credential management example
public class CredentialManagementExample {
public void manageCredentials() {
RangerCredentialManager credManager = new RangerCredentialManager();
// Store credentials securely
char[] dbPassword = "database_password_123".toCharArray();
credManager.storeCredential("database.password", dbPassword);
char[] apiKey = "api_key_xyz789".toCharArray();
credManager.storeCredential("external.api.key", apiKey);
// Retrieve credentials when needed
char[] retrievedPassword = credManager.getCredential("database.password");
if (retrievedPassword != null) {
System.out.println("Database password retrieved: " + new String(retrievedPassword));
// Clear password from memory after use
Arrays.fill(retrievedPassword, '\0');
}
// List all stored credentials
Set<String> aliases = credManager.getCredentialAliases();
System.out.println("Stored credentials: " + aliases);
// Remove specific credential
credManager.removeCredential("external.api.key");
// Clear all credentials on shutdown
credManager.clearAllCredentials();
}
}
// SSL configuration example
public class SSLConfigurationExample {
public void configureSSL() {
try {
// Create configuration with SSL settings
Configuration config = new Configuration();
config.set(RangerSSLConfig.SSL_ENABLED, "true");
config.set(RangerSSLConfig.KEYSTORE_PATH, "/etc/security/keystores/ranger.jks");
config.set(RangerSSLConfig.KEYSTORE_PASSWORD, "keystore_password");
config.set(RangerSSLConfig.TRUSTSTORE_PATH, "/etc/security/truststores/truststore.jks");
config.set(RangerSSLConfig.TRUSTSTORE_PASSWORD, "truststore_password");
// Initialize SSL configuration
RangerSSLConfig sslConfig = new RangerSSLConfig();
sslConfig.init(config);
// Validate configuration
if (!sslConfig.validateConfiguration()) {
throw new Exception("Invalid SSL configuration");
}
if (sslConfig.isSSLEnabled()) {
// Get SSL context for secure communications
SSLContext sslContext = sslConfig.getSSLContext();
// Create SSL socket factory
SSLSocketFactory socketFactory = sslConfig.createSSLSocketFactory();
// Use SSL context for HTTPS connections
HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
System.out.println("SSL configuration successful");
}
} catch (Exception e) {
System.err.println("SSL configuration failed: " + e.getMessage());
}
}
}
// Security utilities usage
public class SecurityUtilitiesExample {
public void useSecurityUtils() {
try {
// Generate secure password
char[] password = RangerSecurityUtils.generateSecurePassword(16);
System.out.println("Generated password length: " + password.length);
// Hash password with salt
byte[] salt = RangerSecurityUtils.generateSalt();
String hashedPassword = RangerSecurityUtils.hashPassword(password, salt);
System.out.println("Password hashed successfully");
// Verify password
boolean isValid = RangerSecurityUtils.verifyPassword(password, hashedPassword, salt);
System.out.println("Password verification: " + isValid);
// Encrypt sensitive data
String sensitiveData = "confidential information";
byte[] encrypted = RangerSecurityUtils.encrypt(
sensitiveData.getBytes(),
"encryption_key_123"
);
System.out.println("Data encrypted, length: " + encrypted.length);
// Decrypt data
byte[] decrypted = RangerSecurityUtils.decrypt(encrypted, "encryption_key_123");
String decryptedText = new String(decrypted);
System.out.println("Decrypted data: " + decryptedText);
// Clear password from memory
Arrays.fill(password, '\0');
} catch (Exception e) {
System.err.println("Security operations failed: " + e.getMessage());
}
}
}
// Complete authentication workflow
public class AuthenticationWorkflowExample {
public void completeAuthenticationWorkflow() {
try {
// Step 1: Initialize SSL configuration
Configuration config = new Configuration();
config.set("ranger.ssl.enabled", "true");
// ... other SSL settings
RangerSSLConfig sslConfig = new RangerSSLConfig();
sslConfig.init(config);
// Step 2: Authenticate with Kerberos
String principal = "ranger/service@EXAMPLE.COM";
String keytab = "/etc/security/keytabs/ranger.keytab";
Subject subject = SecureClientLogin.loginUserFromKeytab(principal, keytab);
RangerAuthenticationContext.setCurrentSubject(subject);
// Step 3: Store additional credentials securely
RangerCredentialManager credManager = new RangerCredentialManager();
credManager.storeCredential("db.password", "db_pass_123".toCharArray());
// Step 4: Perform authenticated operations
if (RangerAuthenticationContext.isAuthenticated()) {
String currentUser = RangerAuthenticationContext.getCurrentUserName();
Set<String> groups = RangerAuthenticationContext.getCurrentUserGroups();
System.out.println("Authenticated user: " + currentUser);
System.out.println("User groups: " + groups);
// Execute privileged operations
RangerAuthenticationContext.doAsPrivileged(
new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
// Perform secure operations here
System.out.println("Executing privileged operation");
return null;
}
},
subject
);
}
} catch (Exception e) {
System.err.println("Authentication workflow failed: " + e.getMessage());
} finally {
// Cleanup
RangerAuthenticationContext.clearCurrentSubject();
}
}
}Common security configuration properties:
ranger.security.kerberos.enabled: Enable/disable Kerberos authenticationranger.security.kerberos.principal: Kerberos principal for serviceranger.security.kerberos.keytab: Path to Kerberos keytab fileranger.security.kerberos.name.rules: Custom Kerberos name mapping rulesranger.ssl.enabled: Enable/disable SSLranger.ssl.keystore.file: Path to SSL keystoreranger.ssl.keystore.password: SSL keystore passwordranger.ssl.truststore.file: Path to SSL truststoreranger.ssl.truststore.password: SSL truststore passwordranger.ssl.protocol: SSL protocol version (TLSv1.2, TLSv1.3)ranger.auth.type: Authentication type (simple, kerberos, ldap)ranger.auth.cache.ttl: Authentication cache time-to-liveranger.auth.retry.attempts: Number of authentication retry attemptsranger.auth.timeout: Authentication timeout in millisecondsInstall with Tessl CLI
npx tessl i tessl/maven-org-apache-ranger--ranger-plugins-common