use of java.security.PrivilegedActionException in project hadoop by apache.
the class TestWebDelegationToken method doAsKerberosUser.
public static <T> T doAsKerberosUser(String principal, String keytab, final Callable<T> callable) throws Exception {
LoginContext loginContext = null;
try {
Set<Principal> principals = new HashSet<Principal>();
principals.add(new KerberosPrincipal(principal));
Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
loginContext = new LoginContext("", subject, null, new KerberosConfiguration(principal, keytab));
loginContext.login();
subject = loginContext.getSubject();
return Subject.doAs(subject, new PrivilegedExceptionAction<T>() {
@Override
public T run() throws Exception {
return callable.call();
}
});
} catch (PrivilegedActionException ex) {
throw ex.getException();
} finally {
if (loginContext != null) {
loginContext.logout();
}
}
}
use of java.security.PrivilegedActionException in project tomcat by apache.
the class SpnegoAuthenticator method doAuthenticate.
@Override
protected boolean doAuthenticate(Request request, HttpServletResponse response) throws IOException {
if (checkForCachedAuthentication(request, response, true)) {
return true;
}
MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders().getValue("authorization");
if (authorization == null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("authenticator.noAuthHeader"));
}
response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
authorization.toBytes();
ByteChunk authorizationBC = authorization.getByteChunk();
if (!authorizationBC.startsWithIgnoreCase("negotiate ", 0)) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("spnegoAuthenticator.authHeaderNotNego"));
}
response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
authorizationBC.setOffset(authorizationBC.getOffset() + 10);
byte[] decoded = Base64.decodeBase64(authorizationBC.getBuffer(), authorizationBC.getOffset(), authorizationBC.getLength());
if (getApplyJava8u40Fix()) {
SpnegoTokenFixer.fix(decoded);
}
if (decoded.length == 0) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("spnegoAuthenticator.authHeaderNoToken"));
}
response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
LoginContext lc = null;
GSSContext gssContext = null;
byte[] outToken = null;
Principal principal = null;
try {
try {
lc = new LoginContext(getLoginConfigName());
lc.login();
} catch (LoginException e) {
log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return false;
}
Subject subject = lc.getSubject();
// Assume the GSSContext is stateless
// TODO: Confirm this assumption
final GSSManager manager = GSSManager.getInstance();
// IBM JDK only understands indefinite lifetime
final int credentialLifetime;
if (JreVendor.IS_IBM_JVM) {
credentialLifetime = GSSCredential.INDEFINITE_LIFETIME;
} else {
credentialLifetime = GSSCredential.DEFAULT_LIFETIME;
}
final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() {
@Override
public GSSCredential run() throws GSSException {
return manager.createCredential(null, credentialLifetime, new Oid("1.3.6.1.5.5.2"), GSSCredential.ACCEPT_ONLY);
}
};
gssContext = manager.createContext(Subject.doAs(subject, action));
outToken = Subject.doAs(lc.getSubject(), new AcceptAction(gssContext, decoded));
if (outToken == null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail"));
}
// Start again
response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
principal = Subject.doAs(subject, new AuthenticateAction(context.getRealm(), gssContext, storeDelegatedCredential));
} catch (GSSException e) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail"), e);
}
response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
} catch (PrivilegedActionException e) {
Throwable cause = e.getCause();
if (cause instanceof GSSException) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("spnegoAuthenticator.serviceLoginFail"), e);
}
} else {
log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e);
}
response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
} finally {
if (gssContext != null) {
try {
gssContext.dispose();
} catch (GSSException e) {
// Ignore
}
}
if (lc != null) {
try {
lc.logout();
} catch (LoginException e) {
// Ignore
}
}
}
// Send response token on success and failure
response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE + " " + Base64.encodeBase64String(outToken));
if (principal != null) {
register(request, response, principal, Constants.SPNEGO_METHOD, principal.getName(), null);
Pattern p = noKeepAliveUserAgents;
if (p != null) {
MessageBytes ua = request.getCoyoteRequest().getMimeHeaders().getValue("user-agent");
if (ua != null && p.matcher(ua.toString()).matches()) {
response.setHeader("Connection", "close");
}
}
return true;
}
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
use of java.security.PrivilegedActionException in project tomcat by apache.
the class SecurityUtil method execute.
/**
* Perform work as a particular <code>Subject</code>. Here the work
* will be granted to a <code>null</code> subject.
*
* @param methodName the method to apply the security restriction
* @param targetObject the <code>Servlet</code> on which the method will
* be called.
* @param targetArguments <code>Object</code> array contains the
* runtime parameters instance.
* @param principal the <code>Principal</code> to which the security
* privilege applies
* @throws Exception an execution error occurred
*/
private static void execute(final Method method, final Object targetObject, final Object[] targetArguments, Principal principal) throws Exception {
try {
Subject subject = null;
PrivilegedExceptionAction<Void> pea = new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
method.invoke(targetObject, targetArguments);
return null;
}
};
// The first argument is always the request object
if (targetArguments != null && targetArguments[0] instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) targetArguments[0];
boolean hasSubject = false;
HttpSession session = request.getSession(false);
if (session != null) {
subject = (Subject) session.getAttribute(Globals.SUBJECT_ATTR);
hasSubject = (subject != null);
}
if (subject == null) {
subject = new Subject();
if (principal != null) {
subject.getPrincipals().add(principal);
}
}
if (session != null && !hasSubject) {
session.setAttribute(Globals.SUBJECT_ATTR, subject);
}
}
Subject.doAsPrivileged(subject, pea, null);
} catch (PrivilegedActionException pe) {
Throwable e;
if (pe.getException() instanceof InvocationTargetException) {
e = pe.getException().getCause();
ExceptionUtils.handleThrowable(e);
} else {
e = pe;
}
if (log.isDebugEnabled()) {
log.debug(sm.getString("SecurityUtil.doAsPrivilege"), e);
}
if (e instanceof UnavailableException)
throw (UnavailableException) e;
else if (e instanceof ServletException)
throw (ServletException) e;
else if (e instanceof IOException)
throw (IOException) e;
else if (e instanceof RuntimeException)
throw (RuntimeException) e;
else
throw new ServletException(e.getMessage(), e);
}
}
use of java.security.PrivilegedActionException in project tomcat by apache.
the class ApplicationFilterChain method doFilter.
// ---------------------------------------------------- FilterChain Methods
/**
* Invoke the next filter in this chain, passing the specified request
* and response. If there are no more filters in this chain, invoke
* the <code>service()</code> method of the servlet itself.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
if (Globals.IS_SECURITY_ENABLED) {
final ServletRequest req = request;
final ServletResponse res = response;
try {
java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws ServletException, IOException {
internalDoFilter(req, res);
return null;
}
});
} catch (PrivilegedActionException pe) {
Exception e = pe.getException();
if (e instanceof ServletException)
throw (ServletException) e;
else if (e instanceof IOException)
throw (IOException) e;
else if (e instanceof RuntimeException)
throw (RuntimeException) e;
else
throw new ServletException(e.getMessage(), e);
}
} else {
internalDoFilter(request, response);
}
}
use of java.security.PrivilegedActionException in project tomcat by apache.
the class PersistentManagerBase method swapIn.
// ------------------------------------------------------ Protected Methods
/**
* Look for a session in the Store and, if found, restore
* it in the Manager's list of active sessions if appropriate.
* The session will be removed from the Store after swapping
* in, but will not be added to the active session list if it
* is invalid or past its expiration.
*
* @param id The id of the session that should be swapped in
* @return restored session, or {@code null}, if none is found
* @throws IOException an IO error occurred
*/
protected Session swapIn(String id) throws IOException {
if (store == null)
return null;
Object swapInLock = null;
/*
* The purpose of this sync and these locks is to make sure that a
* session is only loaded once. It doesn't matter if the lock is removed
* and then another thread enters this method and tries to load the same
* session. That thread will re-create a swapIn lock for that session,
* quickly find that the session is already in sessions, use it and
* carry on.
*/
synchronized (this) {
swapInLock = sessionSwapInLocks.get(id);
if (swapInLock == null) {
swapInLock = new Object();
sessionSwapInLocks.put(id, swapInLock);
}
}
Session session = null;
synchronized (swapInLock) {
// First check to see if another thread has loaded the session into
// the manager
session = sessions.get(id);
if (session == null) {
try {
if (SecurityUtil.isPackageProtectionEnabled()) {
try {
session = AccessController.doPrivileged(new PrivilegedStoreLoad(id));
} catch (PrivilegedActionException ex) {
Exception e = ex.getException();
log.error(sm.getString("persistentManager.swapInException", id), e);
if (e instanceof IOException) {
throw (IOException) e;
} else if (e instanceof ClassNotFoundException) {
throw (ClassNotFoundException) e;
}
}
} else {
session = store.load(id);
}
} catch (ClassNotFoundException e) {
String msg = sm.getString("persistentManager.deserializeError", id);
log.error(msg, e);
throw new IllegalStateException(msg, e);
}
if (session != null && !session.isValid()) {
log.error(sm.getString("persistentManager.swapInInvalid", id));
session.expire();
removeSession(id);
session = null;
}
if (session != null) {
if (log.isDebugEnabled())
log.debug(sm.getString("persistentManager.swapIn", id));
session.setManager(this);
// make sure the listeners know about it.
((StandardSession) session).tellNew();
add(session);
((StandardSession) session).activate();
// endAccess() to ensure timeouts happen correctly.
// access() to keep access count correct or it will end up
// negative
session.access();
session.endAccess();
}
}
}
// Make sure the lock is removed
synchronized (this) {
sessionSwapInLocks.remove(id);
}
return session;
}
Aggregations