1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
|
/*
* 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.catalina.realm;
import java.io.File;
import java.io.IOException;
import java.security.Principal;
import java.util.Map;
import java.util.Map.Entry;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.TextInputCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.catalina.CredentialHandler;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.IntrospectionUtils;
import org.apache.tomcat.util.digester.Digester;
/**
* <p>
* Implementation of the JAAS <strong>LoginModule</strong> interface, primarily for use in testing
* <code>JAASRealm</code>. It utilizes an XML-format data file of username/password/role information identical to that
* supported by <code>org.apache.catalina.realm.MemoryRealm</code>.
* </p>
* <p>
* This class recognizes the following string-valued options, which are specified in the configuration file and passed
* to {@link #initialize(Subject, CallbackHandler, Map, Map)} in the <code>options</code> argument:
* </p>
* <ul>
* <li><strong>pathname</strong> - Relative (to the pathname specified by the "catalina.base" system property) or
* absolute pathname to the XML file containing our user information, in the format supported by {@link MemoryRealm}.
* The default value matches the MemoryRealm default.</li>
* <li><strong>credentialHandlerClassName</strong> - The fully qualified class name of the CredentialHandler to use. If
* not specified, {@link MessageDigestCredentialHandler} will be used.</li>
* <li>Any additional options will be used to identify and call setters on the {@link CredentialHandler}. For example,
* <code>algorithm=SHA256</code> would result in a call to {@link MessageDigestCredentialHandler#setAlgorithm(String)}
* with a parameter of <code>"SHA256"</code></li>
* </ul>
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - This class implements <code>Realm</code> only to satisfy the calling
* requirements of the <code>GenericPrincipal</code> constructor. It does not actually perform the functionality
* required of a <code>Realm</code> implementation.
* </p>
*/
public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
// We need to extend MemoryRealm to avoid class cast
private static final Log log = LogFactory.getLog(JAASMemoryLoginModule.class);
// ----------------------------------------------------- Instance Variables
/**
* The callback handler responsible for answering our requests.
*/
protected CallbackHandler callbackHandler = null;
/**
* Has our own <code>commit()</code> returned successfully?
*/
protected boolean committed = false;
/**
* The configuration information for this <code>LoginModule</code>.
*/
protected Map<String,?> options = null;
/**
* The absolute or relative pathname to the XML configuration file.
*/
protected String pathname = "conf/tomcat-users.xml";
/**
* The <code>Principal</code> identified by our validation, or <code>null</code> if validation failed.
*/
protected Principal principal = null;
/**
* The state information that is shared with other configured <code>LoginModule</code> instances.
*/
protected Map<String,?> sharedState = null;
/**
* The subject for which we are performing authentication.
*/
protected Subject subject = null;
// --------------------------------------------------------- Public Methods
public JAASMemoryLoginModule() {
if (log.isTraceEnabled()) {
log.trace("MEMORY LOGIN MODULE");
}
}
@Override
public boolean abort() throws LoginException {
// If our authentication was not successful, just return false
if (principal == null) {
return false;
}
// Clean up if overall authentication failed
if (committed) {
logout();
} else {
principal = null;
}
if (log.isTraceEnabled()) {
log.trace("Abort");
}
return true;
}
@Override
public boolean commit() throws LoginException {
if (log.isTraceEnabled()) {
log.trace("commit " + principal);
}
// If authentication was not successful, just return false
if (principal == null) {
return false;
}
// Add our Principal to the Subject if needed
if (!subject.getPrincipals().contains(principal)) {
subject.getPrincipals().add(principal);
// Add the roles as additional subjects as per the contract with the
// JAASRealm
if (principal instanceof GenericPrincipal) {
String[] roles = ((GenericPrincipal) principal).getRoles();
for (String role : roles) {
subject.getPrincipals().add(new GenericPrincipal(role));
}
}
}
committed = true;
return true;
}
@Override
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String,?> sharedState,
Map<String,?> options) {
if (log.isTraceEnabled()) {
log.trace("Init");
}
// Save configuration values
this.subject = subject;
this.callbackHandler = callbackHandler;
this.sharedState = sharedState;
this.options = options;
// Perform instance-specific initialization
Object option = options.get("pathname");
if (option instanceof String) {
this.pathname = (String) option;
}
CredentialHandler credentialHandler = null;
option = options.get("credentialHandlerClassName");
if (option instanceof String) {
try {
Class<?> clazz = Class.forName((String) option);
credentialHandler = (CredentialHandler) clazz.getConstructor().newInstance();
} catch (ReflectiveOperationException e) {
throw new IllegalArgumentException(e);
}
}
if (credentialHandler == null) {
credentialHandler = new MessageDigestCredentialHandler();
}
for (Entry<String,?> entry : options.entrySet()) {
if ("pathname".equals(entry.getKey())) {
continue;
}
if ("credentialHandlerClassName".equals(entry.getKey())) {
continue;
}
// Skip any non-String values since any value we are interested in
// will be a String.
if (entry.getValue() instanceof String) {
IntrospectionUtils.setProperty(credentialHandler, entry.getKey(), (String) entry.getValue());
}
}
setCredentialHandler(credentialHandler);
// Load our defined Principals
load();
}
@Override
public boolean login() throws LoginException {
// Set up our CallbackHandler requests
if (callbackHandler == null) {
throw new LoginException(sm.getString("jaasMemoryLoginModule.noCallbackHandler"));
}
Callback[] callbacks = new Callback[10];
callbacks[0] = new NameCallback("Username: ");
callbacks[1] = new PasswordCallback("Password: ", false);
callbacks[2] = new TextInputCallback("nonce");
callbacks[3] = new TextInputCallback("nc");
callbacks[4] = new TextInputCallback("cnonce");
callbacks[5] = new TextInputCallback("qop");
callbacks[6] = new TextInputCallback("realmName");
callbacks[7] = new TextInputCallback("digestA2");
callbacks[8] = new TextInputCallback("algorithm");
callbacks[9] = new TextInputCallback("authMethod");
// Interact with the user to retrieve the username and password
String username;
String password;
String nonce;
String nc;
String cnonce;
String qop;
String realmName;
String digestA2;
String algorithm;
String authMethod;
try {
callbackHandler.handle(callbacks);
username = ((NameCallback) callbacks[0]).getName();
char[] passwordArray = ((PasswordCallback) callbacks[1]).getPassword();
password = (passwordArray == null) ? null : new String(passwordArray);
nonce = ((TextInputCallback) callbacks[2]).getText();
nc = ((TextInputCallback) callbacks[3]).getText();
cnonce = ((TextInputCallback) callbacks[4]).getText();
qop = ((TextInputCallback) callbacks[5]).getText();
realmName = ((TextInputCallback) callbacks[6]).getText();
digestA2 = ((TextInputCallback) callbacks[7]).getText();
algorithm = ((TextInputCallback) callbacks[8]).getText();
authMethod = ((TextInputCallback) callbacks[9]).getText();
} catch (IOException | UnsupportedCallbackException e) {
throw new LoginException(sm.getString("jaasMemoryLoginModule.callbackHandlerError", e.toString()));
}
// Validate the username and password we have received
if (authMethod == null) {
// BASIC or FORM
principal = super.authenticate(username, password);
} else if (authMethod.equals(HttpServletRequest.DIGEST_AUTH)) {
principal = super.authenticate(username, password, nonce, nc, cnonce, qop, realmName, digestA2, algorithm);
} else if (authMethod.equals(HttpServletRequest.CLIENT_CERT_AUTH)) {
principal = super.getPrincipal(username);
} else {
throw new LoginException(sm.getString("jaasMemoryLoginModule.unknownAuthenticationMethod"));
}
if (log.isDebugEnabled()) {
log.debug(sm.getString("jaasMemoryLoginModule.login", username, principal));
}
// Report results based on success or failure
if (principal != null) {
return true;
} else {
throw new FailedLoginException(sm.getString("jaasMemoryLoginModule.invalidCredentials"));
}
}
@Override
public boolean logout() throws LoginException {
subject.getPrincipals().remove(principal);
committed = false;
principal = null;
return true;
}
// ---------------------------------------------------------- Realm Methods
// ------------------------------------------------------ Protected Methods
/**
* Load the contents of our configuration file.
*/
protected void load() {
// Validate the existence of our configuration file
File file = new File(pathname);
if (!file.isAbsolute()) {
String catalinaBase = getCatalinaBase();
if (catalinaBase == null) {
log.error(sm.getString("jaasMemoryLoginModule.noCatalinaBase", pathname));
return;
} else {
file = new File(catalinaBase, pathname);
}
}
if (!file.canRead()) {
log.error(sm.getString("jaasMemoryLoginModule.noConfig", file.getAbsolutePath()));
return;
}
// Load the contents of our configuration file
Digester digester = new Digester();
digester.setValidating(false);
digester.addRuleSet(new MemoryRuleSet());
try {
digester.push(this);
digester.parse(file);
} catch (Exception e) {
log.error(sm.getString("jaasMemoryLoginModule.parseError", file.getAbsolutePath()), e);
} finally {
digester.reset();
}
}
private String getCatalinaBase() {
// Have to get this via a callback as that is the only link we have back
// to the defining Realm. Can't use the system property as that may not
// be set/correct in an embedded scenario
if (callbackHandler == null) {
return null;
}
Callback[] callbacks = new Callback[1];
callbacks[0] = new TextInputCallback("catalinaBase");
String result;
try {
callbackHandler.handle(callbacks);
result = ((TextInputCallback) callbacks[0]).getText();
} catch (IOException | UnsupportedCallbackException e) {
return null;
}
return result;
}
}
|