Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -766,6 +766,11 @@
<url>https://issues.apache.org/jira/browse/ranger</url>
</issueManagement>
<repositories>
<repository>
<id>shibboleth-releases</id>
<name>Shibboleth Release Repository</name>
<url>https://build.shibboleth.net/maven/releases/</url>
</repository>
<repository>
<id>jetbrains-pty4j</id>
<name>jetbrains-intellij-dependencies</name>
Expand Down
61 changes: 60 additions & 1 deletion security-admin/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,12 @@
<artifactId>netty-all</artifactId>
<version>${netty-all.version}</version>
</dependency>
<!-- JAXB API + runtime for Java 11+ (removed from JDK in Java 9) -->
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
Expand All @@ -266,6 +272,13 @@
<artifactId>json-smart</artifactId>
<version>${jsonsmart.version}</version>
</dependency>

<!-- Supporting dependencies for OpenSAML 4.x -->
<dependency>
<groupId>net.shibboleth.utilities</groupId>
<artifactId>java-support</artifactId>
<version>8.4.0</version>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr-runtime</artifactId>
Expand Down Expand Up @@ -686,6 +699,42 @@
<artifactId>cglib</artifactId>
<version>${cglib.version}</version>
</dependency>
<!-- OpenSAML 4.x - Compatible with Spring Security 5.8.x -->
<dependency>
<groupId>org.opensaml</groupId>
<artifactId>opensaml-core</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.opensaml</groupId>
<artifactId>opensaml-saml-api</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.opensaml</groupId>
<artifactId>opensaml-saml-impl</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.opensaml</groupId>
<artifactId>opensaml-security-api</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.opensaml</groupId>
<artifactId>opensaml-security-impl</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.opensaml</groupId>
<artifactId>opensaml-xmlsec-api</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.opensaml</groupId>
<artifactId>opensaml-xmlsec-impl</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
Expand Down Expand Up @@ -778,6 +827,11 @@
<artifactId>spring-security-ldap</artifactId>
<version>${springframework.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-saml2-service-provider</artifactId>
<version>${springframework.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
Expand All @@ -788,7 +842,12 @@
<artifactId>jsr250-api</artifactId>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.9</version>
<scope>runtime</scope>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.apache.ranger</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -511,9 +511,11 @@ private void getSSOSpnegoAuthCheckForAPI(String currentLoginId, HttpServletReque
UserSessionBase session = context != null ? context.getUserSession() : null;
boolean ssoEnabled = session != null ? session.isSSOEnabled() : PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false);
XXPortalUser gjUser = daoManager.getXXPortalUser().findByLoginId(currentLoginId);
String authMethod = PropertiesUtil.getProperty("ranger.authentication.method", "NONE");
boolean samlEnabled = "SAML".equalsIgnoreCase(authMethod);

if (gjUser == null && ((request.getAttribute("spnegoEnabled") != null && (boolean) request.getAttribute("spnegoEnabled")) || (ssoEnabled))) {
logger.debug("User : {} doesn't exist in Ranger DB So creating user as it's SSO or Spnego authenticated", currentLoginId);
if (gjUser == null && ((request.getAttribute("spnegoEnabled") != null && (boolean) request.getAttribute("spnegoEnabled")) || (ssoEnabled) || (samlEnabled))) {
logger.debug("User : {} doesn't exist in Ranger DB So creating user as it's SSO or Spnego or saml authenticated", currentLoginId);

xUserMgr.createServiceConfigUser(currentLoginId);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,7 @@ public class RangerCommonEnums {
public static final int USER_UNIX = 4;
public static final int USER_REPO = 5;
public static final int USER_FEDERATED = 6;
public static final int USER_SAML = 7;

public static final int GROUP_INTERNAL = 0;
public static final int GROUP_EXTERNAL = 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,15 @@ public class XXAuthSession extends XXDBBase implements java.io.Serializable {
*/
public static final int AUTH_TYPE_TRUSTED_PROXY = 4;

/**
* AUTH_TYPE_SAML is an element of enum AuthType. Its value is "AUTH_TYPE_SAML".
*/
public static final int AUTH_TYPE_SAML = 5;

/**
* Max value for enum AuthType_MAX
*/
public static final int AuthType_MAX = 4;
public static final int AuthType_MAX = 5;

@Id
@SequenceGenerator(name = "X_AUTH_SESS_SEQ", sequenceName = "X_AUTH_SESS_SEQ", allocationSize = 1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,7 @@ public VXPortalUser getUserProfile(@Context HttpServletRequest request) {
long inactivityTimeout = PropertiesUtil.getLongProperty("ranger.service.inactivity.timeout", 15 * 60);

configProperties.put("inactivityTimeout", Long.toString(inactivityTimeout));
configProperties.put("authenticationMethod", PropertiesUtil.getProperty("ranger.authentication.method", "NONE"));

VXPortalUser userProfile = userManager.getUserProfileByLoginId();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ranger.security.context;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilderFactory;

import java.io.InputStream;

/**
* Activates the "saml" Spring profile when ranger.authentication.method=SAML.
* This ensures OpenSAML beans are only instantiated when SAML is configured,
* allowing non-SAML deployments to run safely on JDK 8.
* <p>
* IMPORTANT: We cannot use PropertiesUtil here because it is populated by a
* BeanFactoryPostProcessor that runs after ApplicationContextInitializer.
*/
public class RangerApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
private static final Logger LOG = LoggerFactory.getLogger(RangerApplicationContextInitializer.class);

private static final String SAML_AUTH_METHOD = "SAML";
private static final String SAML_PROFILE = "saml";
private static final String AUTH_METHOD_PROPERTY = "ranger.authentication.method";
private static final String CONFIG_RESOURCE = "ranger-admin-site.xml";

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
String authMethod = readAuthMethodFromConfigFile();

if (SAML_AUTH_METHOD.equalsIgnoreCase(authMethod)) {
// Critical safety check for JDK compatibility
try {
Class.forName("org.opensaml.saml.saml2.core.AuthnRequest", false, getClass().getClassLoader());
} catch (ClassNotFoundException | UnsupportedClassVersionError e) {
throw new IllegalStateException(
"SAML 2.0 authentication is enabled (ranger.authentication.method=SAML), " +
"but it requires Java 11 or higher. OpenSAML 4.x is not compatible with Java 8. " +
"Please upgrade Ranger Admin JVM to Java 11+ or change the authentication method.", e);
}
LOG.info("RangerApplicationContextInitializer: activating '{}' Spring profile (ranger.authentication.method={})", SAML_PROFILE, authMethod);
applicationContext.getEnvironment().addActiveProfile(SAML_PROFILE);
} else {
LOG.info("RangerApplicationContextInitializer: SAML profile not activated (ranger.authentication.method={})", authMethod);
}
}

/**
* Reads ranger.authentication.method directly from ranger-admin-site.xml on the
* classpath. This avoids the PropertiesUtil dependency, which is not yet
* initialised at ApplicationContextInitializer time.
*
* @return the configured authentication method, or {@code "NONE"} if the
* property is absent or the file cannot be read.
*/
private String readAuthMethodFromConfigFile() {
try (InputStream is = getClass().getClassLoader().getResourceAsStream(CONFIG_RESOURCE)) {
if (is == null) {
LOG.warn("RangerApplicationContextInitializer: {} not found on classpath; defaulting to NONE", CONFIG_RESOURCE);
return "NONE";
}

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// Harden against XXE
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
dbf.setExpandEntityReferences(false);
dbf.setNamespaceAware(false);

Document doc = dbf.newDocumentBuilder().parse(is);
NodeList properties = doc.getElementsByTagName("property");

for (int i = 0; i < properties.getLength(); i++) {
Element property = (Element) properties.item(i);
NodeList names = property.getElementsByTagName("name");

if (names.getLength() > 0 &&
AUTH_METHOD_PROPERTY.equals(names.item(0).getTextContent().trim())) {
NodeList values = property.getElementsByTagName("value");

if (values.getLength() > 0) {
String value = values.item(0).getTextContent().trim();
LOG.info("RangerApplicationContextInitializer: read {}={} from {}", AUTH_METHOD_PROPERTY, value, CONFIG_RESOURCE);
return value;
}
}
}
} catch (Exception e) {
LOG.error("RangerApplicationContextInitializer: failed to read {} — defaulting to NONE", CONFIG_RESOURCE, e);
}
LOG.warn("RangerApplicationContextInitializer: {} not found in {}; defaulting to NONE", AUTH_METHOD_PROPERTY, CONFIG_RESOURCE);
return "NONE";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@
import org.springframework.security.ldap.search.FilterBasedLdapUserSearch;
import org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticatedPrincipal;
import org.springframework.security.saml2.provider.service.authentication.Saml2Authentication;

import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;
Expand Down Expand Up @@ -144,6 +146,12 @@ public Authentication authenticate(Authentication authentication) throws Authent
} else if ("PAM".equalsIgnoreCase(rangerAuthenticationMethod)) {
authentication = getPamAuthentication(authentication);

if (authentication != null && authentication.isAuthenticated()) {
return authentication;
}
} else if ("SAML".equalsIgnoreCase(rangerAuthenticationMethod)) {
authentication = getSAMLAuthentication(authentication);

if (authentication != null && authentication.isAuthenticated()) {
return authentication;
}
Expand Down Expand Up @@ -215,7 +223,7 @@ public Authentication authenticate(Authentication authentication) throws Authent

@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
return authentication.equals(UsernamePasswordAuthenticationToken.class) || Saml2Authentication.class.isAssignableFrom(authentication);
}

public Authentication getADAuthentication(Authentication authentication) {
Expand Down Expand Up @@ -366,6 +374,60 @@ public Authentication getUnixAuthentication(Authentication authentication) {
return authentication;
}

private Authentication getSAMLAuthentication(Authentication authentication) {
try {
if (!(authentication instanceof Saml2Authentication)) {
logger.debug("Not a SAML authentication, skipping");
return null;
}

String username = authentication.getName();
if (StringUtil.isEmpty(username)) {
throw new BadCredentialsException("No username in SAML authentication");
}

Object principal = authentication.getPrincipal();
if (!(principal instanceof Saml2AuthenticatedPrincipal)) {
logger.warn("Expected Saml2AuthenticatedPrincipal but got {}", principal.getClass().getName());
return null;
}

Saml2AuthenticatedPrincipal samlPrincipal = (Saml2AuthenticatedPrincipal) principal;

// Get username from attribute or NameID
String usernameAttr = PropertiesUtil.getProperty("ranger.saml.attribute.username", "NameID");
if (!"NameID".equalsIgnoreCase(usernameAttr)) {
String attrValue = samlPrincipal.getFirstAttribute(usernameAttr);
if (!StringUtil.isEmpty(attrValue)) {
username = attrValue;
}
}

String email = samlPrincipal.getFirstAttribute("email");
String groupAttrName = PropertiesUtil.getProperty("ranger.saml.attribute.role", "groups");
List<String> groups = samlPrincipal.getAttribute(groupAttrName);
String rangerSamlDefaultRole = PropertiesUtil.getProperty("ranger.saml.default.role", "ROLE_USER");

logger.info("SAML authenticated user: {}, email: {}, groups: {}", username, email, groups);

List<GrantedAuthority> grantedAuths = getAuthorities(username);
if (grantedAuths.isEmpty()) {
logger.info("SAML user '{}' not found in Ranger DB. " + "Assigning session default role: {}", username, rangerSamlDefaultRole);
grantedAuths.add(new SimpleGrantedAuthority(rangerSamlDefaultRole));
}
final UserDetails userDetails = new User(username, "", grantedAuths);
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(userDetails, "", grantedAuths);
result.setDetails(authentication.getDetails());
logger.info("SAML authentication successful for user: {} with authorities: {}", username, grantedAuths);
return result;
} catch (BadCredentialsException e) {
throw e;
} catch (Exception e) {
logger.error("SAML authentication processing failed", e);
throw new BadCredentialsException("SAML processing error", e);
}
}

public String getRangerAuthenticationMethod() {
return rangerAuthenticationMethod;
}
Expand Down
Loading
Loading