use of org.apache.catalina.CredentialHandler in project tomcat by apache.
the class JAASMemoryLoginModule method initialize.
/**
* Initialize this <code>LoginModule</code> with the specified
* configuration information.
*
* @param subject The <code>Subject</code> to be authenticated
* @param callbackHandler A <code>CallbackHandler</code> for communicating
* with the end user as necessary
* @param sharedState State information shared with other
* <code>LoginModule</code> instances
* @param options Configuration information for this specific
* <code>LoginModule</code> instance
*/
@Override
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) {
if (log.isDebugEnabled()) {
log.debug("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.newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException 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;
}
// will be a String.
if (entry.getValue() instanceof String) {
IntrospectionUtils.setProperty(credentialHandler, entry.getKey(), (String) entry.getValue());
}
}
setCredentialHandler(credentialHandler);
// Load our defined Principals
load();
}
use of org.apache.catalina.CredentialHandler in project tomcat by apache.
the class CredentialHandlerSF method storeChildren.
/**
* Store the specified CredentialHandler properties and child (CredentialHandler)
*
* @param aWriter
* PrintWriter to which we are storing
* @param indent
* Number of spaces to indent this element
* @param aCredentialHandler
* CredentialHandler whose properties are being stored
*
* @exception Exception
* if an exception occurs while storing
*/
@Override
public void storeChildren(PrintWriter aWriter, int indent, Object aCredentialHandler, StoreDescription parentDesc) throws Exception {
if (aCredentialHandler instanceof NestedCredentialHandler) {
NestedCredentialHandler nestedCredentialHandler = (NestedCredentialHandler) aCredentialHandler;
// Store nested <CredentialHandler> element
CredentialHandler[] credentialHandlers = nestedCredentialHandler.getCredentialHandlers();
storeElementArray(aWriter, indent, credentialHandlers);
}
}
use of org.apache.catalina.CredentialHandler in project tomcat by apache.
the class StandardContext method startInternal.
/**
* Start 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 synchronized void startInternal() throws LifecycleException {
if (log.isDebugEnabled())
log.debug("Starting " + getBaseName());
// Send j2ee.state.starting notification
if (this.getObjectName() != null) {
Notification notification = new Notification("j2ee.state.starting", this.getObjectName(), sequenceNumber.getAndIncrement());
broadcaster.sendNotification(notification);
}
setConfigured(false);
boolean ok = true;
// ensure the NamingResources follows the correct lifecycle
if (namingResources != null) {
namingResources.start();
}
// Add missing components as necessary
if (getResources() == null) {
// (1) Required by Loader
if (log.isDebugEnabled())
log.debug("Configuring default Resources");
try {
setResources(new StandardRoot(this));
} catch (IllegalArgumentException e) {
log.error(sm.getString("standardContext.resourcesInit"), e);
ok = false;
}
}
if (ok) {
resourcesStart();
}
if (getLoader() == null) {
WebappLoader webappLoader = new WebappLoader(getParentClassLoader());
webappLoader.setDelegate(getDelegate());
setLoader(webappLoader);
}
// An explicit cookie processor hasn't been specified; use the default
if (cookieProcessor == null) {
cookieProcessor = new Rfc6265CookieProcessor();
}
// Initialize character set mapper
getCharsetMapper();
// Post work directory
postWorkDirectory();
// Validate required extensions
boolean dependencyCheck = true;
try {
dependencyCheck = ExtensionValidator.validateApplication(getResources(), this);
} catch (IOException ioe) {
log.error(sm.getString("standardContext.extensionValidationError"), ioe);
dependencyCheck = false;
}
if (!dependencyCheck) {
// do not make application available if dependency check fails
ok = false;
}
// Reading the "catalina.useNaming" environment variable
String useNamingProperty = System.getProperty("catalina.useNaming");
if ((useNamingProperty != null) && (useNamingProperty.equals("false"))) {
useNaming = false;
}
if (ok && isUseNaming()) {
if (getNamingContextListener() == null) {
NamingContextListener ncl = new NamingContextListener();
ncl.setName(getNamingContextName());
ncl.setExceptionOnFailedWrite(getJndiExceptionOnFailedWrite());
addLifecycleListener(ncl);
setNamingContextListener(ncl);
}
}
// Standard container startup
if (log.isDebugEnabled())
log.debug("Processing standard container startup");
// Binding thread
ClassLoader oldCCL = bindThread();
try {
if (ok) {
// Start our subordinate components, if any
Loader loader = getLoader();
if (loader instanceof Lifecycle) {
((Lifecycle) loader).start();
}
// since the loader just started, the webapp classloader is now
// created.
setClassLoaderProperty("clearReferencesRmiTargets", getClearReferencesRmiTargets());
setClassLoaderProperty("clearReferencesStopThreads", getClearReferencesStopThreads());
setClassLoaderProperty("clearReferencesStopTimerThreads", getClearReferencesStopTimerThreads());
setClassLoaderProperty("clearReferencesHttpClientKeepAliveThread", getClearReferencesHttpClientKeepAliveThread());
// By calling unbindThread and bindThread in a row, we setup the
// current Thread CCL to be the webapp classloader
unbindThread(oldCCL);
oldCCL = bindThread();
// Initialize logger again. Other components might have used it
// too early, so it should be reset.
logger = null;
getLogger();
Realm realm = getRealmInternal();
if (null != realm) {
if (realm instanceof Lifecycle) {
((Lifecycle) realm).start();
}
// Place the CredentialHandler into the ServletContext so
// applications can have access to it. Wrap it in a "safe"
// handler so application's can't modify it.
CredentialHandler safeHandler = new CredentialHandler() {
@Override
public boolean matches(String inputCredentials, String storedCredentials) {
return getRealmInternal().getCredentialHandler().matches(inputCredentials, storedCredentials);
}
@Override
public String mutate(String inputCredentials) {
return getRealmInternal().getCredentialHandler().mutate(inputCredentials);
}
};
context.setAttribute(Globals.CREDENTIAL_HANDLER, safeHandler);
}
// Notify our interested LifecycleListeners
fireLifecycleEvent(Lifecycle.CONFIGURE_START_EVENT, null);
// Start our child containers, if not already started
for (Container child : findChildren()) {
if (!child.getState().isAvailable()) {
child.start();
}
}
// if any
if (pipeline instanceof Lifecycle) {
((Lifecycle) pipeline).start();
}
// Acquire clustered manager
Manager contextManager = null;
Manager manager = getManager();
if (manager == null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("standardContext.cluster.noManager", Boolean.valueOf((getCluster() != null)), Boolean.valueOf(distributable)));
}
if ((getCluster() != null) && distributable) {
try {
contextManager = getCluster().createManager(getName());
} catch (Exception ex) {
log.error("standardContext.clusterFail", ex);
ok = false;
}
} else {
contextManager = new StandardManager();
}
}
// Configure default manager if none was specified
if (contextManager != null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("standardContext.manager", contextManager.getClass().getName()));
}
setManager(contextManager);
}
if (manager != null && (getCluster() != null) && distributable) {
//let the cluster know that there is a context that is distributable
//and that it has its own manager
getCluster().registerManager(manager);
}
}
if (!getConfigured()) {
log.error(sm.getString("standardContext.configurationFail"));
ok = false;
}
// We put the resources into the servlet context
if (ok)
getServletContext().setAttribute(Globals.RESOURCES_ATTR, getResources());
if (ok) {
if (getInstanceManager() == null) {
javax.naming.Context context = null;
if (isUseNaming() && getNamingContextListener() != null) {
context = getNamingContextListener().getEnvContext();
}
Map<String, Map<String, String>> injectionMap = buildInjectionMap(getIgnoreAnnotations() ? new NamingResourcesImpl() : getNamingResources());
setInstanceManager(new DefaultInstanceManager(context, injectionMap, this, this.getClass().getClassLoader()));
}
getServletContext().setAttribute(InstanceManager.class.getName(), getInstanceManager());
InstanceManagerBindings.bind(getLoader().getClassLoader(), getInstanceManager());
}
// Create context attributes that will be required
if (ok) {
getServletContext().setAttribute(JarScanner.class.getName(), getJarScanner());
}
// Set up the context init params
mergeParameters();
// Call ServletContainerInitializers
for (Map.Entry<ServletContainerInitializer, Set<Class<?>>> entry : initializers.entrySet()) {
try {
entry.getKey().onStartup(entry.getValue(), getServletContext());
} catch (ServletException e) {
log.error(sm.getString("standardContext.sciFail"), e);
ok = false;
break;
}
}
// Configure and call application event listeners
if (ok) {
if (!listenerStart()) {
log.error(sm.getString("standardContext.listenerFail"));
ok = false;
}
}
// change constraints
if (ok) {
checkConstraintsForUncoveredMethods(findConstraints());
}
try {
// Start manager
Manager manager = getManager();
if (manager instanceof Lifecycle) {
((Lifecycle) manager).start();
}
} catch (Exception e) {
log.error(sm.getString("standardContext.managerFail"), e);
ok = false;
}
// Configure and call application filters
if (ok) {
if (!filterStart()) {
log.error(sm.getString("standardContext.filterFail"));
ok = false;
}
}
// Load and initialize all "load on startup" servlets
if (ok) {
if (!loadOnStartup(findChildren())) {
log.error(sm.getString("standardContext.servletFail"));
ok = false;
}
}
// Start ContainerBackgroundProcessor thread
super.threadStart();
} finally {
// Unbinding thread
unbindThread(oldCCL);
}
// Set available status depending upon startup success
if (ok) {
if (log.isDebugEnabled())
log.debug("Starting completed");
} else {
log.error(sm.getString("standardContext.startFailed", getName()));
}
startTime = System.currentTimeMillis();
// Send j2ee.state.running notification
if (ok && (this.getObjectName() != null)) {
Notification notification = new Notification("j2ee.state.running", this.getObjectName(), sequenceNumber.getAndIncrement());
broadcaster.sendNotification(notification);
}
// The WebResources implementation caches references to JAR files. On
// some platforms these references may lock the JAR files. Since web
// application start is likely to have read from lots of JARs, trigger
// a clean-up now.
getResources().gc();
// Reinitializing if something went wrong
if (!ok) {
setState(LifecycleState.FAILED);
} else {
setState(LifecycleState.STARTING);
}
}
use of org.apache.catalina.CredentialHandler in project tomcat by apache.
the class RealmSF method storeChildren.
/**
* Store the specified Realm properties and child (Realm)
*
* @param aWriter
* PrintWriter to which we are storing
* @param indent
* Number of spaces to indent this element
* @param aRealm
* Realm whose properties are being stored
*
* @exception Exception
* if an exception occurs while storing
*/
@Override
public void storeChildren(PrintWriter aWriter, int indent, Object aRealm, StoreDescription parentDesc) throws Exception {
if (aRealm instanceof CombinedRealm) {
CombinedRealm combinedRealm = (CombinedRealm) aRealm;
// Store nested <Realm> element
Realm[] realms = combinedRealm.getNestedRealms();
storeElementArray(aWriter, indent, realms);
}
// Store nested <CredentialHandler> element
CredentialHandler credentialHandler = ((Realm) aRealm).getCredentialHandler();
if (credentialHandler != null) {
storeElement(aWriter, indent, credentialHandler);
}
}
use of org.apache.catalina.CredentialHandler in project tomcat by apache.
the class RealmBase method main.
/**
* Generate a stored credential string for the given password and associated
* parameters.
* <p>The following parameters are supported:</p>
* <ul>
* <li><b>-a</b> - The algorithm to use to generate the stored
* credential. If not specified a default of SHA-512 will be
* used.</li>
* <li><b>-e</b> - The encoding to use for any byte to/from character
* conversion that may be necessary. If not specified, the
* system encoding ({@link Charset#defaultCharset()}) will
* be used.</li>
* <li><b>-i</b> - The number of iterations to use when generating the
* stored credential. If not specified, the default for the
* CredentialHandler will be used.</li>
* <li><b>-s</b> - The length (in bytes) of salt to generate and store as
* part of the credential. If not specified, the default for
* the CredentialHandler will be used.</li>
* <li><b>-k</b> - The length (in bits) of the key(s), if any, created while
* generating the credential. If not specified, the default
* for the CredentialHandler will be used.</li>
* <li><b>-h</b> - The fully qualified class name of the CredentialHandler
* to use. If not specified, the built-in handlers will be
* tested in turn and the first one to accept the specified
* algorithm will be used.</li>
* </ul>
* <p>This generation process currently supports the following
* CredentialHandlers, the correct one being selected based on the algorithm
* specified:</p>
* <ul>
* <li>{@link MessageDigestCredentialHandler}</li>
* <li>{@link SecretKeyCredentialHandler}</li>
* </ul>
* @param args The parameters passed on the command line
*/
public static void main(String[] args) {
// Use negative values since null is not an option to indicate 'not set'
int saltLength = -1;
int iterations = -1;
int keyLength = -1;
// Default
String encoding = Charset.defaultCharset().name();
// Default values for these depend on whether either of them are set on
// the command line
String algorithm = null;
String handlerClassName = null;
if (args.length == 0) {
usage();
return;
}
int argIndex = 0;
while (args.length > argIndex + 2 && args[argIndex].length() == 2 && args[argIndex].charAt(0) == '-') {
switch(args[argIndex].charAt(1)) {
case 'a':
{
algorithm = args[argIndex + 1];
break;
}
case 'e':
{
encoding = args[argIndex + 1];
break;
}
case 'i':
{
iterations = Integer.parseInt(args[argIndex + 1]);
break;
}
case 's':
{
saltLength = Integer.parseInt(args[argIndex + 1]);
break;
}
case 'k':
{
keyLength = Integer.parseInt(args[argIndex + 1]);
break;
}
case 'h':
{
handlerClassName = args[argIndex + 1];
break;
}
default:
{
usage();
return;
}
}
argIndex += 2;
}
// or may nor support -a and may or may not supply a sensible default
if (algorithm == null && handlerClassName == null) {
algorithm = "SHA-512";
}
CredentialHandler handler = null;
if (handlerClassName == null) {
for (Class<? extends DigestCredentialHandlerBase> clazz : credentialHandlerClasses) {
try {
handler = clazz.newInstance();
if (IntrospectionUtils.setProperty(handler, "algorithm", algorithm)) {
break;
}
} catch (InstantiationException | IllegalAccessException e) {
// This isn't good.
throw new RuntimeException(e);
}
}
} else {
try {
Class<?> clazz = Class.forName(handlerClassName);
handler = (DigestCredentialHandlerBase) clazz.newInstance();
IntrospectionUtils.setProperty(handler, "algorithm", algorithm);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
if (handler == null) {
throw new RuntimeException(new NoSuchAlgorithmException(algorithm));
}
IntrospectionUtils.setProperty(handler, "encoding", encoding);
if (iterations > 0) {
IntrospectionUtils.setProperty(handler, "iterations", Integer.toString(iterations));
}
if (saltLength > -1) {
IntrospectionUtils.setProperty(handler, "saltLength", Integer.toString(saltLength));
}
if (keyLength > 0) {
IntrospectionUtils.setProperty(handler, "keyLength", Integer.toString(keyLength));
}
for (; argIndex < args.length; argIndex++) {
String credential = args[argIndex];
System.out.print(credential + ":");
System.out.println(handler.mutate(credential));
}
}
Aggregations