use of java.security.PrivilegedActionException in project wildfly by wildfly.
the class Utils method makeCallWithKerberosAuthn.
/**
* Returns response body for the given URL request as a String. It also checks if the returned HTTP status code is the
* expected one. If the server returns {@link HttpServletResponse#SC_UNAUTHORIZED} and an username is provided, then the
* given user is authenticated against Kerberos and a new request is executed under the new subject.
*
* @param uri URI to which the request should be made
* @param user Username
* @param pass Password
* @param expectedStatusCode expected status code returned from the requested server
* @return HTTP response body
* @throws IOException
* @throws URISyntaxException
* @throws PrivilegedActionException
* @throws LoginException
*/
public static String makeCallWithKerberosAuthn(final URI uri, final String user, final String pass, final int expectedStatusCode) throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
LOGGER.trace("Requesting URI: " + uri);
Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new JBossNegotiateSchemeFactory(true)).build();
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullHCCredentials());
final Krb5LoginConfiguration krb5Configuration = new Krb5LoginConfiguration(getLoginConfiguration());
try (final CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credentialsProvider).build()) {
final HttpGet httpGet = new HttpGet(uri);
final HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
return EntityUtils.toString(response.getEntity());
}
final HttpEntity entity = response.getEntity();
final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
assertTrue("WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
final Set<String> authnHeaderValues = new HashSet<String>();
for (final Header header : authnHeaders) {
authnHeaderValues.add(header.getValue());
}
assertTrue("WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
}
if (entity != null)
EntityUtils.consume(entity);
// Use our custom configuration to avoid reliance on external config
Configuration.setConfiguration(krb5Configuration);
// 1. Authenticate to Kerberos.
final LoginContext lc = loginWithKerberos(krb5Configuration, user, pass);
// 2. Perform the work as authenticated Subject.
final String responseBody = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<String>() {
public String run() throws Exception {
final HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode);
return EntityUtils.toString(response.getEntity());
}
});
lc.logout();
return responseBody;
} finally {
krb5Configuration.resetConfiguration();
}
}
use of java.security.PrivilegedActionException in project wildfly by wildfly.
the class Utils method makeHttpCallWithFallback.
/**
* Creates request against SPNEGO protected web-app with FORM fallback. It tries to login using SPNEGO first - if it fails,
* FORM is used.
*
* @param contextUrl
* @param page
* @param user
* @param pass
* @param expectedStatusCode
* @return
* @throws IOException
* @throws URISyntaxException
* @throws PrivilegedActionException
* @throws LoginException
*/
public static String makeHttpCallWithFallback(final String contextUrl, final String page, final String user, final String pass, final int expectedStatusCode) throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
final String strippedContextUrl = StringUtils.stripEnd(contextUrl, "/");
final String url = strippedContextUrl + page;
LOGGER.trace("Requesting URL: " + url);
String unauthorizedPageBody = null;
final Krb5LoginConfiguration krb5Configuration = new Krb5LoginConfiguration(getLoginConfiguration());
Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new JBossNegotiateSchemeFactory(true)).build();
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullHCCredentials());
final CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credentialsProvider).setRedirectStrategy(REDIRECT_STRATEGY).setConnectionManager(new BasicHttpClientConnectionManager()).build();
try {
final HttpGet httpGet = new HttpGet(url);
final HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
return EntityUtils.toString(response.getEntity());
}
final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
assertTrue("WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
final Set<String> authnHeaderValues = new HashSet<String>();
for (final Header header : authnHeaders) {
authnHeaderValues.add(header.getValue());
}
assertTrue("WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));
LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
unauthorizedPageBody = EntityUtils.toString(response.getEntity());
// Use our custom configuration to avoid reliance on external config
Configuration.setConfiguration(krb5Configuration);
// 1. Authenticate to Kerberos.
final LoginContext lc = loginWithKerberos(krb5Configuration, user, pass);
// 2. Perform the work as authenticated Subject.
final String responseBody = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<String>() {
public String run() throws Exception {
final HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode);
return EntityUtils.toString(response.getEntity());
}
});
lc.logout();
return responseBody;
} catch (LoginException e) {
assertNotNull(unauthorizedPageBody);
assertTrue(unauthorizedPageBody.contains("j_security_check"));
HttpPost httpPost = new HttpPost(strippedContextUrl + "/j_security_check");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("j_username", user));
nameValuePairs.add(new BasicNameValuePair("j_password", pass));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
final HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode);
return EntityUtils.toString(response.getEntity());
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpClient.close();
// reset login configuration
krb5Configuration.resetConfiguration();
}
}
use of java.security.PrivilegedActionException in project intellij-community by JetBrains.
the class SystemClassLoaderAction method initSystemClassLoader.
private static synchronized void initSystemClassLoader() {
if (!sclSet) {
if (scl != null)
throw new IllegalStateException("recursive call");
sun.misc.Launcher l = sun.misc.Launcher.getLauncher();
if (l != null) {
Throwable oops = null;
scl = l.getClassLoader();
try {
PrivilegedExceptionAction a;
a = new SystemClassLoaderAction(scl);
scl = (ClassLoader) AccessController.doPrivileged(a);
} catch (PrivilegedActionException pae) {
oops = pae.getCause();
if (oops instanceof InvocationTargetException) {
oops = oops.getCause();
}
}
if (oops != null) {
if (oops instanceof Error) {
throw (Error) oops;
} else {
// wrap the exception
throw new Error(oops);
}
}
}
sclSet = true;
}
}
use of java.security.PrivilegedActionException 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.
SecurityContext legacyContext = null;
if (this.legacySecurityDomain != null && (identityPrincipal != null || principal != null)) {
// we don't have any real way to establish trust in identity based auth so we just use
// the SASCurrent as a credential, and a custom legacy login module can make a decision for us.
final Object finalCredential = identityPrincipal != null ? this.sasCurrent : credential;
final Principal finalPrincipal = identityPrincipal != null ? identityPrincipal : principal;
if (WildFlySecurityManager.isChecking()) {
legacyContext = AccessController.doPrivileged((PrivilegedExceptionAction<SecurityContext>) () -> {
SecurityContext sc = SecurityContextFactory.createSecurityContext(this.legacySecurityDomain);
sc.getUtil().createSubjectInfo(finalPrincipal, finalCredential, null);
return sc;
});
} else {
legacyContext = SecurityContextFactory.createSecurityContext(this.legacySecurityDomain);
legacyContext.getUtil().createSubjectInfo(finalPrincipal, finalCredential, null);
}
}
if (legacyContext != null) {
setSecurityContextOnAssociation(legacyContext);
}
try {
final InterceptorContext interceptorContext = new InterceptorContext();
if (legacyContext != null) {
interceptorContext.putPrivateData(SecurityContext.class, legacyContext);
}
prepareInterceptorContext(op, params, interceptorContext);
retVal = this.componentView.invoke(interceptorContext);
} finally {
if (legacyContext != null) {
clearSecurityContextOnAssociation();
}
}
}
}
}
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 java.security.PrivilegedActionException in project wildfly by wildfly.
the class AuthorizationInterceptor method processInvocation.
@Override
public Object processInvocation(InterceptorContext context) throws Exception {
final Component component = context.getPrivateData(Component.class);
if (component instanceof EJBComponent == false) {
throw EjbLogger.ROOT_LOGGER.unexpectedComponent(component, EJBComponent.class);
}
final Method invokedMethod = context.getMethod();
final ComponentView componentView = context.getPrivateData(ComponentView.class);
final String viewClassOfInvokedMethod = componentView.getViewClass().getName();
// shouldn't really happen if the interceptor was setup correctly. But let's be safe and do a check
if (!this.viewClassName.equals(viewClassOfInvokedMethod) || !this.viewMethod.equals(invokedMethod)) {
throw EjbLogger.ROOT_LOGGER.failProcessInvocation(this.getClass().getName(), invokedMethod, viewClassOfInvokedMethod, viewMethod, viewClassName);
}
final EJBComponent ejbComponent = (EJBComponent) component;
final ServerSecurityManager securityManager = ejbComponent.getSecurityManager();
final MethodInterfaceType methodIntfType = this.getMethodInterfaceType(componentView.getPrivateData(MethodIntf.class));
// set the JACC contextID before calling the security manager.
final String previousContextID = setContextID(this.contextID);
try {
if (WildFlySecurityManager.isChecking()) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public ProtectionDomain run() {
if (!securityManager.authorize(ejbComponent.getComponentName(), componentView.getProxyClass().getProtectionDomain().getCodeSource(), methodIntfType.name(), AuthorizationInterceptor.this.viewMethod, AuthorizationInterceptor.this.getMethodRolesAsPrincipals(), AuthorizationInterceptor.this.contextID)) {
throw EjbLogger.ROOT_LOGGER.invocationOfMethodNotAllowed(invokedMethod, ejbComponent.getComponentName());
}
return null;
}
});
} catch (PrivilegedActionException e) {
throw e.getException();
}
} else {
if (!securityManager.authorize(ejbComponent.getComponentName(), componentView.getProxyClass().getProtectionDomain().getCodeSource(), methodIntfType.name(), this.viewMethod, this.getMethodRolesAsPrincipals(), this.contextID)) {
throw EjbLogger.ROOT_LOGGER.invocationOfMethodNotAllowed(invokedMethod, ejbComponent.getComponentName());
}
}
// successful authorization, let the invocation proceed
return context.proceed();
} finally {
// reset the previous JACC contextID.
setContextID(previousContextID);
}
}
Aggregations