use of org.wildfly.security.auth.client.AuthenticationContext in project wildfly by wildfly.
the class ElytronSASClientInterceptor method createInitialContextToken.
/**
* Create an encoded {@link InitialContextToken} with an username/password pair obtained from an Elytron client configuration
* matched by the specified {@link URI} and purpose.
*
* @param uri the target {@link URI}.
* @param purpose a {@link String} representing the purpose of the configuration that will be used.
* @param secMech a reference to the {@link CompoundSecMech} that was found in the {@link ClientRequestInfo}.
* @return the encoded {@link InitialContextToken}, if a valid username is obtained from the matched configuration;
* an empty {@code byte[]} otherwise;
* @throws Exception if an error occurs while building the encoded {@link InitialContextToken}.
*/
private byte[] createInitialContextToken(final URI uri, final String purpose, final CompoundSecMech secMech) throws Exception {
AuthenticationContext authContext = this.authContext == null ? AuthenticationContext.captureCurrent() : this.authContext;
// obtain the configuration that matches the URI and purpose.
final AuthenticationConfiguration configuration = AUTH_CONFIG_CLIENT.getAuthenticationConfiguration(uri, authContext, -1, null, null, purpose);
// get the callback handler from the configuration and use it to obtain a username/password pair.
final CallbackHandler handler = AUTH_CONFIG_CLIENT.getCallbackHandler(configuration);
final NameCallback nameCallback = new NameCallback("Username: ");
final PasswordCallback passwordCallback = new PasswordCallback("Password: ", false);
try {
handler.handle(new Callback[] { nameCallback, passwordCallback });
} catch (UnsupportedCallbackException e) {
return NO_AUTHENTICATION_TOKEN;
}
// if the name callback contains a valid username we create the initial context token.
if (nameCallback.getName() != null && !nameCallback.getName().equals(AnonymousPrincipal.getInstance().getName())) {
byte[] encodedTargetName = secMech.as_context_mech.target_name;
String name = nameCallback.getName();
if (name.indexOf('@') < 0) {
byte[] decodedTargetName = CSIv2Util.decodeGssExportedName(encodedTargetName);
String targetName = new String(decodedTargetName, StandardCharsets.UTF_8);
// "@default"
name += "@" + targetName;
}
byte[] username = name.getBytes(StandardCharsets.UTF_8);
byte[] password = {};
if (passwordCallback.getPassword() != null)
password = new String(passwordCallback.getPassword()).getBytes(StandardCharsets.UTF_8);
// create the initial context token and ASN.1-encode it, as defined in RFC 2743.
InitialContextToken authenticationToken = new InitialContextToken(username, password, encodedTargetName);
return CSIv2Util.encodeInitialContextToken(authenticationToken, codec);
}
return NO_AUTHENTICATION_TOKEN;
}
use of org.wildfly.security.auth.client.AuthenticationContext in project wildfly by wildfly.
the class SwitchIdentityTestCase method callUsingClientLoginModule.
// Private methods -------------------------------------------------------
/**
* Perform the tests using the ClientLoginModule and LoginContext API to set the desired Principal.
*/
private void callUsingClientLoginModule(String userName, boolean hasRole1, boolean hasRole2) throws Exception {
AuthenticationContext authenticationContext = setupAuthenticationContext(userName);
authenticationContext.runCallable(() -> {
// register the client side interceptor
final EJBClientContext ejbClientContext = EJBClientContext.getCurrent().withAddedInterceptors(new ClientSecurityInterceptor());
ejbClientContext.runCallable(() -> {
final Manage targetBean = EJBUtil.lookupEJB(TargetBean.class, Manage.class);
final Manage bridgeBean = EJBUtil.lookupEJB(BridgeBean.class, Manage.class);
//test direct access
testMethodAccess(targetBean, ManageMethodEnum.ALLROLES, true);
testMethodAccess(targetBean, ManageMethodEnum.ROLE1, hasRole1);
testMethodAccess(targetBean, ManageMethodEnum.ROLE2, hasRole2);
//test security context propagation
testMethodAccess(bridgeBean, ManageMethodEnum.ALLROLES, true);
testMethodAccess(bridgeBean, ManageMethodEnum.ROLE1, hasRole1);
testMethodAccess(bridgeBean, ManageMethodEnum.ROLE2, hasRole2);
return null;
});
return null;
});
}
use of org.wildfly.security.auth.client.AuthenticationContext in project quickstart by wildfly.
the class RemoteClient method main.
public static void main(String[] args) throws Exception {
AuthenticationConfiguration common = AuthenticationConfiguration.empty().setSaslMechanismSelector(SaslMechanismSelector.NONE.addMechanism("DIGEST-MD5"));
AuthenticationConfiguration quickstartUser = common.useName("quickstartUser").usePassword("quickstartPwd1!");
final AuthenticationContext authCtx1 = AuthenticationContext.empty().with(MatchRule.ALL, quickstartUser);
System.out.println(authCtx1.runCallable(callable));
AuthenticationConfiguration superUser = common.useName("superUser").usePassword("superPwd1!");
final AuthenticationContext authCtx2 = AuthenticationContext.empty().with(MatchRule.ALL, superUser);
System.out.println(authCtx2.runCallable(callable));
}
use of org.wildfly.security.auth.client.AuthenticationContext in project wildfly by wildfly.
the class EjbCorbaServant method _invoke.
/**
* Receives IIOP requests to this servant's <code>EJBObject</code>s
* and forwards them to the bean container, through the JBoss
* <code>MBean</code> server.
*/
public OutputStream _invoke(final String opName, final InputStream in, final ResponseHandler handler) {
EjbLogger.ROOT_LOGGER.tracef("EJBObject invocation: %s", opName);
SkeletonStrategy op = methodInvokerMap.get(opName);
if (op == null) {
EjbLogger.ROOT_LOGGER.debugf("Unable to find opname '%s' valid operations:%s", opName, methodInvokerMap.keySet());
throw new BAD_OPERATION(opName);
}
final NamespaceContextSelector selector = componentView.getComponent().getNamespaceContextSelector();
final ClassLoader oldCl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
NamespaceContextSelector.pushCurrentSelector(selector);
try {
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);
org.omg.CORBA_2_3.portable.OutputStream out;
try {
Object retVal;
if (!home && opName.equals("_get_handle")) {
retVal = new HandleImplIIOP(orb.object_to_string(_this_object()));
} else if (home && opName.equals("_get_homeHandle")) {
retVal = homeHandle;
} else if (home && opName.equals("_get_EJBMetaData")) {
retVal = ejbMetaData;
} else {
Principal identityPrincipal = null;
Principal principal = null;
Object credential = null;
if (this.sasCurrent != null) {
final byte[] incomingIdentity = this.sasCurrent.get_incoming_principal_name();
// we have an identity token, which is a trust based mechanism
if (incomingIdentity != null && incomingIdentity.length > 0) {
String name = new String(incomingIdentity, StandardCharsets.UTF_8);
int domainIndex = name.indexOf('@');
if (domainIndex > 0)
name = name.substring(0, domainIndex);
identityPrincipal = new NamePrincipal(name);
}
final byte[] incomingUsername = this.sasCurrent.get_incoming_username();
if (incomingUsername != null && incomingUsername.length > 0) {
final byte[] incomingPassword = this.sasCurrent.get_incoming_password();
String name = new String(incomingUsername, StandardCharsets.UTF_8);
int domainIndex = name.indexOf('@');
if (domainIndex > 0) {
name = name.substring(0, domainIndex);
}
principal = new NamePrincipal(name);
credential = new String(incomingPassword, StandardCharsets.UTF_8).toCharArray();
}
}
final Object[] params = op.readParams((org.omg.CORBA_2_3.portable.InputStream) in);
if (!this.home && opName.equals("isIdentical") && params.length == 1) {
// handle isIdentical specially
Object val = params[0];
retVal = val instanceof org.omg.CORBA.Object && handleIsIdentical((org.omg.CORBA.Object) val);
} else {
if (this.securityDomain != null) {
// an elytron security domain is available: authenticate and authorize the client before invoking the component.
SecurityIdentity identity = this.securityDomain.getAnonymousSecurityIdentity();
AuthenticationConfiguration authenticationConfiguration = AuthenticationConfiguration.EMPTY;
if (identityPrincipal != null) {
// permission to run as the identity token principal.
if (principal != null) {
char[] password = (char[]) credential;
authenticationConfiguration = authenticationConfiguration.useName(principal.getName()).usePassword(password);
SecurityIdentity authenticatedIdentity = this.authenticate(principal, password);
identity = authenticatedIdentity.createRunAsIdentity(identityPrincipal.getName(), true);
} else {
// no TLS nor initial context token found - check if the anonymous identity has
// permission to run as the identity principal.
identity = this.securityDomain.getAnonymousSecurityIdentity().createRunAsIdentity(identityPrincipal.getName(), true);
}
} else if (principal != null) {
char[] password = (char[]) credential;
// we have an initial context token containing a username/password pair.
authenticationConfiguration = authenticationConfiguration.useName(principal.getName()).usePassword(password);
identity = this.authenticate(principal, password);
}
final InterceptorContext interceptorContext = new InterceptorContext();
this.prepareInterceptorContext(op, params, interceptorContext);
try {
final AuthenticationContext context = AuthenticationContext.captureCurrent().with(MatchRule.ALL.matchProtocol("iiop"), authenticationConfiguration);
retVal = identity.runAs((PrivilegedExceptionAction<Object>) () -> context.run((PrivilegedExceptionAction<Object>) () -> this.componentView.invoke(interceptorContext)));
} catch (PrivilegedActionException e) {
throw e.getCause();
}
} else {
// legacy security behavior: setup the security context if a SASCurrent is available and invoke the component.
// One of the EJB security interceptors will authenticate and authorize the client.
final InterceptorContext interceptorContext = new InterceptorContext();
prepareInterceptorContext(op, params, interceptorContext);
retVal = this.componentView.invoke(interceptorContext);
}
}
}
out = (org.omg.CORBA_2_3.portable.OutputStream) handler.createReply();
if (op.isNonVoid()) {
op.writeRetval(out, retVal);
}
} catch (Throwable e) {
EjbLogger.ROOT_LOGGER.trace("Exception in EJBObject invocation", e);
if (e instanceof MBeanException) {
e = ((MBeanException) e).getTargetException();
}
RmiIdlUtil.rethrowIfCorbaSystemException(e);
out = (org.omg.CORBA_2_3.portable.OutputStream) handler.createExceptionReply();
op.writeException(out, e);
}
return out;
} finally {
NamespaceContextSelector.popCurrentSelector();
WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldCl);
}
}
use of org.wildfly.security.auth.client.AuthenticationContext in project wildfly by wildfly.
the class ElytronSASClientInterceptor method send_request.
@Override
public void send_request(ClientRequestInfo ri) throws ForwardRequest {
try {
CompoundSecMech secMech = CSIv2Util.getMatchingSecurityMech(ri, codec, EstablishTrustInClient.value, /* client supports */
(short) 0);
if (secMech == null) {
return;
}
// these "null tokens" will be changed if needed.
IdentityToken identityToken = ABSENT_IDENTITY_TOKEN;
byte[] encodedAuthenticationToken = NO_AUTHENTICATION_TOKEN;
final URI uri = this.getURI(ri);
if (uri == null) {
return;
}
SecurityDomain domain = getCurrentSecurityDomain();
SecurityIdentity currentIdentity = null;
if (domain != null) {
currentIdentity = domain.getCurrentSecurityIdentity();
}
final AuthenticationContext authContext;
if (this.authContext != null) {
authContext = this.authContext;
} else if (currentIdentity == null || currentIdentity.isAnonymous()) {
authContext = AuthenticationContext.captureCurrent();
} else {
authContext = AuthenticationContext.empty().with(MatchRule.ALL, AuthenticationConfiguration.empty().useForwardedIdentity(domain));
}
if ((secMech.sas_context_mech.target_supports & IdentityAssertion.value) != 0) {
final AuthenticationConfiguration configuration = AUTH_CONFIG_CLIENT.getAuthenticationConfiguration(uri, authContext, -1, null, null);
final Principal principal = AUTH_CONFIG_CLIENT.getPrincipal(configuration);
if (principal != null && principal != AnonymousPrincipal.getInstance()) {
// The name scope needs to be externalized.
String name = principal.getName();
if (name.indexOf('@') < 0) {
// hardcoded (REVISIT!)
name += "@default";
}
byte[] principalName = name.getBytes(StandardCharsets.UTF_8);
// encode the principal name as mandated by RFC2743.
byte[] encodedName = CSIv2Util.encodeGssExportedName(principalName);
// encapsulate the encoded name.
Any any = ORB.init().create_any();
byte[] encapsulatedEncodedName;
GSS_NT_ExportedNameHelper.insert(any, encodedName);
try {
encapsulatedEncodedName = codec.encode_value(any);
} catch (InvalidTypeForEncoding e) {
throw IIOPLogger.ROOT_LOGGER.unexpectedException(e);
}
// create identity token.
identityToken = new IdentityToken();
identityToken.principal_name(encapsulatedEncodedName);
} else if ((secMech.sas_context_mech.supported_identity_types & ITTAnonymous.value) != 0) {
// no run-as or caller identity and the target supports ITTAnonymous: use the anonymous identity.
identityToken = new IdentityToken();
identityToken.anonymous(true);
}
// target might require an additional initial context token with a username/password pair for authentication.
if ((secMech.as_context_mech.target_requires & EstablishTrustInClient.value) != 0) {
encodedAuthenticationToken = this.createInitialContextToken(uri, secMech);
}
} else if ((secMech.as_context_mech.target_supports & EstablishTrustInClient.value) != 0) {
// target doesn't require an identity token but supports username/password authentication - try to build
// an initial context token using the configuration.
encodedAuthenticationToken = this.createInitialContextToken(uri, secMech);
}
if (identityToken != ABSENT_IDENTITY_TOKEN || encodedAuthenticationToken != NO_AUTHENTICATION_TOKEN) {
// at least one non-null token was created, create EstablishContext message with it.
EstablishContext message = new // stateless ctx id
EstablishContext(// stateless ctx id
0, NO_AUTHORIZATION_TOKEN, identityToken, encodedAuthenticationToken);
// create SAS context with the EstablishContext message.
SASContextBody contextBody = new SASContextBody();
contextBody.establish_msg(message);
// stuff the SAS context into the outgoing request.
final Any any = ORB.init().create_any();
SASContextBodyHelper.insert(any, contextBody);
ServiceContext sc = new ServiceContext(SAS_CONTEXT_ID, codec.encode_value(any));
ri.add_request_service_context(sc, true);
}
} catch (Exception e) {
throw IIOPLogger.ROOT_LOGGER.unexpectedException(e);
}
}
Aggregations