null.
*
* @param username Username of the Principal to look up
*/
@Override
public Principal authenticate(String username) {
if (username == null) {
return null;
}
if (containerLog.isTraceEnabled()) {
containerLog.trace(sm.getString("realmBase.authenticateSuccess", username));
}
return getPrincipal(username);
}
/**
* Return the Principal associated with the specified username and
* credentials, if there is one; otherwise return null.
*
* @param username Username of the Principal to look up
* @param credentials Password or other credentials to use in
* authenticating this username
* @return the associated principal, or null if there is none.
*/
@Override
public Principal authenticate(String username, String credentials) {
// No user or no credentials
// Can't possibly authenticate, don't bother doing anything.
if(username == null || credentials == null) {
if (containerLog.isTraceEnabled()) {
containerLog.trace(sm.getString("realmBase.authenticateFailure",
username));
}
return null;
}
// Look up the user's credentials
String serverCredentials = getPassword(username);
if (serverCredentials == null) {
// User was not found
// Waste a bit of time as not to reveal that the user does not exist.
getCredentialHandler().mutate(credentials);
if (containerLog.isTraceEnabled()) {
containerLog.trace(sm.getString("realmBase.authenticateFailure",
username));
}
return null;
}
boolean validated = getCredentialHandler().matches(credentials, serverCredentials);
if (validated) {
if (containerLog.isTraceEnabled()) {
containerLog.trace(sm.getString("realmBase.authenticateSuccess",
username));
}
return getPrincipal(username);
} else {
if (containerLog.isTraceEnabled()) {
containerLog.trace(sm.getString("realmBase.authenticateFailure",
username));
}
return null;
}
}
/**
* Try to authenticate with the specified username, which
* matches the digest calculated using the given parameters using the
* method described in RFC 2617 (which is a superset of RFC 2069).
*
* @param username Username of the Principal to look up
* @param clientDigest Digest which has been submitted by the client
* @param nonce Unique (or supposedly unique) token which has been used
* for this request
* @param nc the nonce counter
* @param cnonce the client chosen nonce
* @param qop the "quality of protection" (nc and cnonce
* will only be used, if qop is not null).
* @param realm Realm name
* @param md5a2 Second MD5 digest used to calculate the digest :
* MD5(Method + ":" + uri)
* @return the associated principal, or null if there is none.
*/
@Override
public Principal authenticate(String username, String clientDigest,
String nonce, String nc, String cnonce,
String qop, String realm,
String md5a2) {
// In digest auth, digests are always lower case
String md5a1 = getDigest(username, realm);
if (md5a1 == null)
return null;
md5a1 = md5a1.toLowerCase(Locale.ENGLISH);
String serverDigestValue;
if (qop == null) {
serverDigestValue = md5a1 + ":" + nonce + ":" + md5a2;
} else {
serverDigestValue = md5a1 + ":" + nonce + ":" + nc + ":" +
cnonce + ":" + qop + ":" + md5a2;
}
byte[] valueBytes = null;
try {
valueBytes = serverDigestValue.getBytes(getDigestCharset());
} catch (UnsupportedEncodingException uee) {
log.error("Illegal digestEncoding: " + getDigestEncoding(), uee);
throw new IllegalArgumentException(uee.getMessage());
}
String serverDigest = MD5Encoder.encode(ConcurrentMessageDigest.digestMD5(valueBytes));
if (log.isDebugEnabled()) {
log.debug("Digest : " + clientDigest + " Username:" + username
+ " ClientDigest:" + clientDigest + " nonce:" + nonce
+ " nc:" + nc + " cnonce:" + cnonce + " qop:" + qop
+ " realm:" + realm + "md5a2:" + md5a2
+ " Server digest:" + serverDigest);
}
if (serverDigest.equals(clientDigest)) {
return getPrincipal(username);
}
return null;
}
/**
* Return the Principal associated with the specified chain of X509
* client certificates. If there is none, return null.
*
* @param certs Array of client certificates, with the first one in
* the array being the certificate of the client itself.
*/
@Override
public Principal authenticate(X509Certificate certs[]) {
if ((certs == null) || (certs.length < 1))
return null;
// Check the validity of each certificate in the chain
if (log.isDebugEnabled())
log.debug("Authenticating client certificate chain");
if (validate) {
for (int i = 0; i < certs.length; i++) {
if (log.isDebugEnabled())
log.debug(" Checking validity for '" +
certs[i].getSubjectDN().getName() + "'");
try {
certs[i].checkValidity();
} catch (Exception e) {
if (log.isDebugEnabled())
log.debug(" Validity exception", e);
return null;
}
}
}
// Check the existence of the client Principal in our database
return getPrincipal(certs[0]);
}
/**
* {@inheritDoc}
*/
@Override
public Principal authenticate(GSSContext gssContext, boolean storeCred) {
if (gssContext.isEstablished()) {
GSSName gssName = null;
try {
gssName = gssContext.getSrcName();
} catch (GSSException e) {
log.warn(sm.getString("realmBase.gssNameFail"), e);
}
if (gssName!= null) {
GSSCredential gssCredential = null;
if (storeCred) {
if (gssContext.getCredDelegState()) {
try {
gssCredential = gssContext.getDelegCred();
} catch (GSSException e) {
log.warn(sm.getString(
"realmBase.delegatedCredentialFail", gssName), e);
}
} else {
if (log.isDebugEnabled()) {
log.debug(sm.getString(
"realmBase.credentialNotDelegated", gssName));
}
}
}
return getPrincipal(gssName, gssCredential);
}
} else {
log.error(sm.getString("realmBase.gssContextNotEstablished"));
}
// Fail in all other cases
return null;
}
/**
* {@inheritDoc}
*/
@Override
public Principal authenticate(GSSName gssName, GSSCredential gssCredential) {
if (gssName == null) {
return null;
}
return getPrincipal(gssName, gssCredential);
}
/**
* Execute a periodic task, such as reloading, etc. This method will be
* invoked inside the classloading context of this container. Unexpected
* throwables will be caught and logged.
*/
@Override
public void backgroundProcess() {
// NOOP in base class
}
/**
* Return the SecurityConstraints configured to guard the request URI for
* this request, or null if there is no such constraint.
*
* @param request Request we are processing
* @param context Context the Request is mapped to
*/
@Override
public SecurityConstraint [] findSecurityConstraints(Request request,
Context context) {
ArrayListtrue if this constraint is satisfied and processing
* should continue, or false otherwise.
*
* @param request Request we are processing
* @param response Response we are creating
* @param constraints Security constraint we are enforcing
* @param context The Context to which client of this class is attached.
*
* @exception IOException if an input/output error occurs
*/
@Override
public boolean hasResourcePermission(Request request,
Response response,
SecurityConstraint []constraints,
Context context)
throws IOException {
if (constraints == null || constraints.length == 0)
return true;
// Which user principal have we already authenticated?
Principal principal = request.getPrincipal();
boolean status = false;
boolean denyfromall = false;
for(int i=0; i < constraints.length; i++) {
SecurityConstraint constraint = constraints[i];
String roles[];
if (constraint.getAllRoles()) {
// * means all roles defined in web.xml
roles = request.getContext().findSecurityRoles();
} else {
roles = constraint.findAuthRoles();
}
if (roles == null)
roles = new String[0];
if (log.isDebugEnabled())
log.debug(" Checking roles " + principal);
if (constraint.getAuthenticatedUsers() && principal != null) {
if (log.isDebugEnabled()) {
log.debug("Passing all authenticated users");
}
status = true;
} else if (roles.length == 0 && !constraint.getAllRoles() &&
!constraint.getAuthenticatedUsers()) {
if(constraint.getAuthConstraint()) {
if( log.isDebugEnabled() )
log.debug("No roles");
status = false; // No listed roles means no access at all
denyfromall = true;
break;
}
if(log.isDebugEnabled())
log.debug("Passing all access");
status = true;
} else if (principal == null) {
if (log.isDebugEnabled())
log.debug(" No user authenticated, cannot grant access");
} else {
for (int j = 0; j < roles.length; j++) {
if (hasRole(request.getWrapper(), principal, roles[j])) {
status = true;
if( log.isDebugEnabled() )
log.debug( "Role found: " + roles[j]);
}
else if( log.isDebugEnabled() )
log.debug( "No role found: " + roles[j]);
}
}
}
if (!denyfromall && allRolesMode != AllRolesMode.STRICT_MODE &&
!status && principal != null) {
if (log.isDebugEnabled()) {
log.debug("Checking for all roles mode: " + allRolesMode);
}
// Check for an all roles(role-name="*")
for (int i = 0; i < constraints.length; i++) {
SecurityConstraint constraint = constraints[i];
String roles[];
// If the all roles mode exists, sets
if (constraint.getAllRoles()) {
if (allRolesMode == AllRolesMode.AUTH_ONLY_MODE) {
if (log.isDebugEnabled()) {
log.debug("Granting access for role-name=*, auth-only");
}
status = true;
break;
}
// For AllRolesMode.STRICT_AUTH_ONLY_MODE there must be zero roles
roles = request.getContext().findSecurityRoles();
if (roles.length == 0 && allRolesMode == AllRolesMode.STRICT_AUTH_ONLY_MODE) {
if (log.isDebugEnabled()) {
log.debug("Granting access for role-name=*, strict auth-only");
}
status = true;
break;
}
}
}
}
// Return a "Forbidden" message denying access to this resource
if(!status) {
response.sendError
(HttpServletResponse.SC_FORBIDDEN,
sm.getString("realmBase.forbidden"));
}
return status;
}
/**
* {@inheritDoc}
*
* This method or {@link #hasRoleInternal(Principal,
* String)} can be overridden by Realm implementations, but the default is
* adequate when an instance of GenericPrincipal is used to
* represent authenticated Principals from this Realm.
*/
@Override
public boolean hasRole(Wrapper wrapper, Principal principal, String role) {
// Check for a role alias
if (wrapper != null) {
String realRole = wrapper.findSecurityReference(role);
if (realRole != null) {
role = realRole;
}
}
// Should be overridden in JAASRealm - to avoid pretty inefficient conversions
if (principal == null || role == null) {
return false;
}
boolean result = hasRoleInternal(principal, role);
if (log.isDebugEnabled()) {
String name = principal.getName();
if (result)
log.debug(sm.getString("realmBase.hasRoleSuccess", name, role));
else
log.debug(sm.getString("realmBase.hasRoleFailure", name, role));
}
return result;
}
/**
* Check if the specified Principal has the specified
* security role, within the context of this Realm.
*
* This method or {@link #hasRoleInternal(Principal,
* String)} can be overridden by Realm implementations, but the default is
* adequate when an instance of GenericPrincipal is used to
* represent authenticated Principals from this Realm.
*
* @param principal Principal for whom the role is to be checked
* @param role Security role to be checked
*
* @return true if the specified Principal has the specified
* security role, within the context of this Realm; otherwise return
* false.
*/
protected boolean hasRoleInternal(Principal principal, String role) {
// Should be overridden in JAASRealm - to avoid pretty inefficient conversions
if (!(principal instanceof GenericPrincipal)) {
return false;
}
GenericPrincipal gp = (GenericPrincipal) principal;
return gp.hasRole(role);
}
/**
* Enforce any user data constraint required by the security constraint
* guarding this request URI. Return true if this constraint
* was not violated and processing should continue, or false
* if we have created a response already.
*
* @param request Request we are processing
* @param response Response we are creating
* @param constraints Security constraint being checked
*
* @exception IOException if an input/output error occurs
*/
@Override
public boolean hasUserDataPermission(Request request,
Response response,
SecurityConstraint []constraints)
throws IOException {
// Is there a relevant user data constraint?
if (constraints == null || constraints.length == 0) {
if (log.isDebugEnabled())
log.debug(" No applicable security constraint defined");
return true;
}
for(int i=0; i < constraints.length; i++) {
SecurityConstraint constraint = constraints[i];
String userConstraint = constraint.getUserConstraint();
if (userConstraint == null) {
if (log.isDebugEnabled())
log.debug(" No applicable user data constraint defined");
return true;
}
if (userConstraint.equals(TransportGuarantee.NONE.name())) {
if (log.isDebugEnabled())
log.debug(" User data constraint has no restrictions");
return true;
}
}
// Validate the request against the user data constraint
if (request.getRequest().isSecure()) {
if (log.isDebugEnabled())
log.debug(" User data constraint already satisfied");
return true;
}
// Initialize variables we need to determine the appropriate action
int redirectPort = request.getConnector().getRedirectPort();
// Is redirecting disabled?
if (redirectPort <= 0) {
if (log.isDebugEnabled())
log.debug(" SSL redirect is disabled");
response.sendError
(HttpServletResponse.SC_FORBIDDEN,
request.getRequestURI());
return false;
}
// Redirect to the corresponding SSL port
StringBuilder file = new StringBuilder();
String protocol = "https";
String host = request.getServerName();
// Protocol
file.append(protocol).append("://").append(host);
// Host with port
if(redirectPort != 443) {
file.append(":").append(redirectPort);
}
// URI
file.append(request.getRequestURI());
String requestedSessionId = request.getRequestedSessionId();
if ((requestedSessionId != null) &&
request.isRequestedSessionIdFromURL()) {
file.append(";");
file.append(SessionConfig.getSessionUriParamName(
request.getContext()));
file.append("=");
file.append(requestedSessionId);
}
String queryString = request.getQueryString();
if (queryString != null) {
file.append('?');
file.append(queryString);
}
if (log.isDebugEnabled())
log.debug(" Redirecting to " + file.toString());
response.sendRedirect(file.toString(), transportGuaranteeRedirectStatus);
return false;
}
/**
* Remove a property change listener from this component.
*
* @param listener The listener to remove
*/
@Override
public void removePropertyChangeListener(PropertyChangeListener listener) {
support.removePropertyChangeListener(listener);
}
@Override
public boolean isAvailable() {
return true;
}
@Override
protected void initInternal() throws LifecycleException {
super.initInternal();
// We want logger as soon as possible
if (container != null) {
this.containerLog = container.getLogger();
}
x509UsernameRetriever = createUsernameRetriever(x509UsernameRetrieverClassName);
}
/**
* Prepare for the beginning of active use of the public methods of this
* component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
*
* @exception LifecycleException if this component detects a fatal error
* that prevents this component from being used
*/
@Override
protected void startInternal() throws LifecycleException {
if (credentialHandler == null) {
credentialHandler = new MessageDigestCredentialHandler();
}
setState(LifecycleState.STARTING);
}
/**
* Gracefully terminate the active use of the public methods of this
* component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
*
* @exception LifecycleException if this component detects a fatal error
* that needs to be reported
*/
@Override
protected void stopInternal() throws LifecycleException {
setState(LifecycleState.STOPPING);
}
/**
* Return a String representation of this component.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("Realm[");
sb.append(getName());
sb.append(']');
return sb.toString();
}
// ------------------------------------------------------ Protected Methods
protected boolean hasMessageDigest() {
CredentialHandler ch = credentialHandler;
if (ch instanceof MessageDigestCredentialHandler) {
return ((MessageDigestCredentialHandler) ch).getAlgorithm() != null;
}
return false;
}
/**
* Return the digest associated with given principal's user name.
* @param username the user name
* @param realmName the realm name
* @return the digest for the specified user
*/
protected String getDigest(String username, String realmName) {
if (hasMessageDigest()) {
// Use pre-generated digest
return getPassword(username);
}
String digestValue = username + ":" + realmName + ":"
+ getPassword(username);
byte[] valueBytes = null;
try {
valueBytes = digestValue.getBytes(getDigestCharset());
} catch (UnsupportedEncodingException uee) {
log.error("Illegal digestEncoding: " + getDigestEncoding(), uee);
throw new IllegalArgumentException(uee.getMessage());
}
return MD5Encoder.encode(ConcurrentMessageDigest.digestMD5(valueBytes));
}
private String getDigestEncoding() {
CredentialHandler ch = credentialHandler;
if (ch instanceof MessageDigestCredentialHandler) {
return ((MessageDigestCredentialHandler) ch).getEncoding();
}
return null;
}
private Charset getDigestCharset() throws UnsupportedEncodingException {
String charset = getDigestEncoding();
if (charset == null) {
return StandardCharsets.ISO_8859_1;
} else {
return B2CConverter.getCharset(charset);
}
}
/**
* @return a short name for this Realm implementation, for use in
* log messages.
*
* @deprecated This will be removed in Tomcat 9 onwards. Use
* {@link Class#getSimpleName()} instead.
*/
@Deprecated
protected abstract String getName();
/**
* Get the password for the specified user.
* @param username The user name
* @return the password associated with the given principal's user name.
*/
protected abstract String getPassword(String username);
/**
* Get the principal associated with the specified certificate.
* @param usercert The user certificate
* @return the Principal associated with the given certificate.
*/
protected Principal getPrincipal(X509Certificate usercert) {
String username = x509UsernameRetriever.getUsername(usercert);
if(log.isDebugEnabled())
log.debug(sm.getString("realmBase.gotX509Username", username));
return(getPrincipal(username));
}
/**
* Get the principal associated with the specified user.
* @param username The user name
* @return the Principal associated with the given user name.
*/
protected abstract Principal getPrincipal(String username);
/**
* Get the principal associated with the specified user name.
*
* @param username The user name
* @param gssCredential the GSS credential of the principal
* @return the principal associated with the given user name.
* @deprecated This will be removed in Tomcat 10 onwards. Use
* {@link #getPrincipal(GSSName, GSSCredential)} instead.
*/
@Deprecated
protected Principal getPrincipal(String username,
GSSCredential gssCredential) {
Principal p = getPrincipal(username);
if (p instanceof GenericPrincipal) {
((GenericPrincipal) p).setGssCredential(gssCredential);
}
return p;
}
/**
* Get the principal associated with the specified {@link GSSName}.
*
* @param gssName The GSS name
* @param gssCredential the GSS credential of the principal
* @return the principal associated with the given user name.
*/
protected Principal getPrincipal(GSSName gssName,
GSSCredential gssCredential) {
String name = gssName.toString();
if (isStripRealmForGss()) {
int i = name.indexOf('@');
if (i > 0) {
// Zero so we don't leave a zero length name
name = name.substring(0, i);
}
}
Principal p = getPrincipal(name);
if (p instanceof GenericPrincipal) {
((GenericPrincipal) p).setGssCredential(gssCredential);
}
return p;
}
/**
* Return the Server object that is the ultimate parent for the container
* with which this Realm is associated. If the server cannot be found (eg
* because the container hierarchy is not complete), null is
* returned.
* @return the Server associated with the realm
*/
protected Server getServer() {
Container c = container;
if (c instanceof Context) {
c = c.getParent();
}
if (c instanceof Host) {
c = c.getParent();
}
if (c instanceof Engine) {
Service s = ((Engine)c).getService();
if (s != null) {
return s.getServer();
}
}
return null;
}
// --------------------------------------------------------- Static Methods
/**
* Digest password using the algorithm specified and convert the result to a
* corresponding hex string.
*
* @param credentials Password or other credentials to use in authenticating
* this username
* @param algorithm Algorithm used to do the digest
* @param encoding Character encoding of the string to digest
*
* @return The digested credentials as a hex string or the original plain
* text credentials if an error occurs.
*
* @deprecated Unused. This will be removed in Tomcat 9.
*/
@Deprecated
public static final String Digest(String credentials, String algorithm,
String encoding) {
try {
// Obtain a new message digest with "digest" encryption
MessageDigest md =
(MessageDigest) MessageDigest.getInstance(algorithm).clone();
// encode the credentials
// Should use the digestEncoding, but that's not a static field
if (encoding == null) {
md.update(credentials.getBytes());
} else {
md.update(credentials.getBytes(encoding));
}
// Digest the credentials and return as hexadecimal
return (HexUtils.toHexString(md.digest()));
} catch(Exception ex) {
log.error(ex);
return credentials;
}
}
/**
* Generate a stored credential string for the given password and associated
* parameters.
* The following parameters are supported:
*This generation process currently supports the following * CredentialHandlers, the correct one being selected based on the algorithm * specified:
*