private GenericMessageInfo createMessageInfo(final HttpServerExchange exchange, final SecurityContext securityContext) { ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); GenericMessageInfo messageInfo = new GenericMessageInfo(); messageInfo.setRequestMessage(servletRequestContext.getServletRequest()); messageInfo.setResponseMessage(servletRequestContext.getServletResponse()); messageInfo.getMap().put("javax.security.auth.message.MessagePolicy.isMandatory", isMandatory(servletRequestContext).toString()); // additional context data, useful to provide access to Undertow resources during the modules processing messageInfo.getMap().put(SECURITY_CONTEXT_ATTACHMENT_KEY, securityContext); messageInfo.getMap().put(HTTP_SERVER_EXCHANGE_ATTACHMENT_KEY, exchange); return messageInfo; }
@Override public void handleRequest(final HttpServerExchange exchange) throws Exception { SecurityContext sc = exchange.getAttachment(UndertowSecurityAttachments.SECURITY_CONTEXT_ATTACHMENT); RunAsIdentityMetaData identity = null; RunAs old = null; try { final ServletChain servlet = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getCurrentServlet(); identity = runAsIdentityMetaDataMap.get(servlet.getManagedServlet().getServletInfo().getName()); RunAsIdentity runAsIdentity = null; if (identity != null) { UndertowLogger.ROOT_LOGGER.tracef("%s, runAs: %s", servlet.getManagedServlet().getServletInfo().getName(), identity); runAsIdentity = new RunAsIdentity(identity.getRoleName(), identity.getPrincipalName(), identity.getRunAsRoles()); } old = SecurityActions.setRunAsIdentity(runAsIdentity, sc); // Perform the request next.handleRequest(exchange); } finally { if (identity != null) { SecurityActions.setRunAsIdentity(old, sc); } } }
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { String old = exchange.getAttachment(OLD_RELATIVE_PATH); if(!old.equals(exchange.getRelativePath())) { ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); ServletPathMatch info = src.getDeployment().getServletPaths().getServletHandlerByPath(exchange.getRelativePath()); src.setCurrentServlet(info.getServletChain()); src.setServletPathMatch(info); } handler.handleRequest(exchange); } };
public static ServletRequest getActiveRequest() { ServletRequestContext current; if(System.getSecurityManager() == null) { current = ServletRequestContext.current(); } else { current = AccessController.doPrivileged(CURRENT_CONTEXT); } if(current == null) { return null; } return current.getServletRequest(); } }
private void dispatchRequest(final HttpServerExchange exchange, final ServletRequestContext servletRequestContext, final ServletChain servletChain, final DispatcherType dispatcherType) throws Exception { HttpHandler next=null; try{ //lets get access of superclass private fields using reflection: Field nextField = ServletInitialHandler.class.getDeclaredField("next"); nextField.setAccessible(true); next = (HttpHandler)nextField.get(this); nextField.setAccessible(false); }catch(NoSuchFieldException | IllegalAccessException e){ throw new ServletException(e); } servletRequestContext.setDispatcherType(dispatcherType); servletRequestContext.setCurrentServlet(servletChain); if (dispatcherType == DispatcherType.REQUEST || dispatcherType == DispatcherType.ASYNC) { super.handleFirstRequest(exchange, servletChain, servletRequestContext, servletRequestContext.getServletRequest(), servletRequestContext.getServletResponse()); } else { next.handleRequest(exchange); } }
@Override public void handleRequest(final HttpServerExchange exchange) throws Exception { final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); ServletRequest request = servletRequestContext.getServletRequest(); if (request.getDispatcherType() == DispatcherType.REQUEST) { List<SingleConstraintMatch> constraints = servletRequestContext.getRequiredConstrains(); SecurityContext sc = exchange.getSecurityContext(); if (!authorizationManager.canAccessResource(constraints, sc.getAuthenticatedAccount(), servletRequestContext.getCurrentServlet().getManagedServlet().getServletInfo(), servletRequestContext.getOriginalRequest(), servletRequestContext.getDeployment())) { HttpServletResponse response = (HttpServletResponse) servletRequestContext.getServletResponse(); response.sendError(StatusCodes.FORBIDDEN); return; } } next.handleRequest(exchange); }
static String buildApplicationIdentifier(final ServletRequestContext attachment) { ServletRequest servletRequest = attachment.getServletRequest(); return servletRequest.getServletContext().getVirtualServerName() + " " + servletRequest.getServletContext().getContextPath(); }
final HttpServletResponseImpl oResponse = new HttpServletResponseImpl(exchange, convergedServletContext.getDelegatedContext()); final HttpServletRequestImpl oRequest = new HttpServletRequestImpl(exchange, convergedServletContext.getDelegatedContext()); final ServletRequestContext servletRequestContext = new ServletRequestContext(convergedServletContext.getDeployment(), oRequest, oResponse, info); servletRequestContext.setServletRequest(request); servletRequestContext.setServletResponse(response); servletRequestContext.setServletPathMatch(info);
final ServletRequest oldReq = servletRequestContext.getServletRequest(); final ServletResponse oldResp = servletRequestContext.getServletResponse(); try { servletRequestContext.setServletRequest(request); servletRequestContext.setServletResponse(response); int index = location++; if (index >= filters.size()) { } finally { location--; servletRequestContext.setServletRequest(oldReq); servletRequestContext.setServletResponse(oldResp);
public void doErrorDispatch(int sc, String error) throws IOException { writer = null; responseState = ResponseState.NONE; resetBuffer(); treatAsCommitted = false; final String location = servletContext.getDeployment().getErrorPages().getErrorLocation(sc); if (location != null) { RequestDispatcherImpl requestDispatcher = new RequestDispatcherImpl(location, servletContext); final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); try { requestDispatcher.error(servletRequestContext, servletRequestContext.getServletRequest(), servletRequestContext.getServletResponse(), exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getCurrentServlet().getManagedServlet().getServletInfo().getName(), error); } catch (ServletException e) { throw new RuntimeException(e); } } else if (error != null) { setContentType("text/html"); setCharacterEncoding("UTF-8"); if(servletContext.getDeployment().getDeploymentInfo().isEscapeErrorMessage()) { getWriter().write("<html><head><title>Error</title></head><body>" + escapeHtml(error) + "</body></html>"); } else { getWriter().write("<html><head><title>Error</title></head><body>" + error + "</body></html>"); } getWriter().close(); } responseDone(); }
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { try { next.handleRequest(exchange); } finally { try { JASPICContext context = exchange.getAttachment(JASPICContext.ATTACHMENT_KEY); if (!JASPICAuthenticationMechanism.wasAuthExceptionThrown(exchange) && context != null) { ServletRequestContext requestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); String applicationIdentifier = JASPICAuthenticationMechanism.buildApplicationIdentifier(requestContext); UndertowLogger.ROOT_LOGGER.debugf("secureResponse for layer [%s] and applicationContextIdentifier [%s].", JASPICAuthenticationMechanism.JASPI_HTTP_SERVLET_LAYER, applicationIdentifier); context.getSam().secureResponse(context.getMessageInfo(), new Subject(), JASPICAuthenticationMechanism.JASPI_HTTP_SERVLET_LAYER, applicationIdentifier, context.getCbh()); // A SAM can unwrap the HTTP request/response objects - update the servlet request context with the values found in the message info. ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); servletRequestContext.setServletRequest((HttpServletRequest) context.getMessageInfo().getRequestMessage()); servletRequestContext.setServletResponse((HttpServletResponse) context.getMessageInfo().getResponseMessage()); } } catch (Exception e) { UndertowLogger.ROOT_LOGGER.errorInvokingSecureResponse(e); } } }
@Override public boolean canAccessResource(List<SingleConstraintMatch> mappedConstraints, Account account, ServletInfo servletInfo, HttpServletRequest request, Deployment deployment) { ServletRequestContext src = ServletRequestContext.current(); boolean baseDecision = delegate.canAccessResource(mappedConstraints, account, servletInfo, request, deployment); boolean authzDecision = false; roles.addAll(account.getRoles()); authzDecision = helper.checkResourcePermission(contextMap, request, src.getServletResponse(), caller, PolicyContext.getContextID(), requestURI(src.getExchange()), roles); boolean finalDecision = baseDecision && authzDecision && hasUserDataPermission(request, src.getOriginalResponse(), account, mappedConstraints);
@Override public OutputStream getOutputStream() { ServletResponse response = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getServletResponse(); try { return response.getOutputStream(); } catch (IOException e) { throw new RuntimeException(e); } }
static boolean isFormAuthentication(HttpServerExchange exchange) { ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); List<AuthenticationMechanism> mechanisms = src.getDeployment().getAuthenticationMechanisms(); for (AuthenticationMechanism mech : mechanisms) { if (mech instanceof ServletFormAuthenticationMechanism) return true; } return false; } }
@Override public void run() { servletRequestContext.getCurrentServletContext().invokeRunnable(exchange, run); } });
@Override protected void handleRedirectBack(final HttpServerExchange exchange) { final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); HttpServletResponse resp = (HttpServletResponse) servletRequestContext.getServletResponse(); HttpSessionImpl httpSession = servletRequestContext.getCurrentServletContext().getSession(exchange, false); if (httpSession != null) { Session session; if (System.getSecurityManager() == null) { session = httpSession.getSession(); } else { session = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(httpSession)); } String path = (String) session.getAttribute(SESSION_KEY); if (path != null) { try { resp.sendRedirect(path); } catch (IOException e) { throw new RuntimeException(e); } } } }
@Override public AsyncContext startAsync(final ServletRequest servletRequest, final ServletResponse servletResponse) throws IllegalStateException { final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); if (!servletContext.getDeployment().getDeploymentInfo().isAllowNonStandardWrappers()) { if (servletRequestContext.getOriginalRequest() != servletRequest) { if (!(servletRequest instanceof ServletRequestWrapper)) { throw UndertowServletMessages.MESSAGES.requestWasNotOriginalOrWrapper(servletRequest); } } if (servletRequestContext.getOriginalResponse() != servletResponse) { if (!(servletResponse instanceof ServletResponseWrapper)) { throw UndertowServletMessages.MESSAGES.responseWasNotOriginalOrWrapper(servletResponse); } } } if (!isAsyncSupported()) { throw UndertowServletMessages.MESSAGES.startAsyncNotAllowed(); } else if (asyncStarted) { throw UndertowServletMessages.MESSAGES.asyncAlreadyStarted(); } asyncStarted = true; servletRequestContext.setServletRequest(servletRequest); servletRequestContext.setServletResponse(servletResponse); return asyncContext = new AsyncContextImpl(exchange, servletRequest, servletResponse, servletRequestContext, true, asyncContext); }
@Override public void dispatchToServlet(final HttpServerExchange exchange, final ServletChain servletchain, final DispatcherType dispatcherType) throws Exception { final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); DispatcherType oldDispatch = servletRequestContext.getDispatcherType(); ServletChain oldChain = servletRequestContext.getCurrentServlet(); try { dispatchRequest(exchange, servletRequestContext, servletchain, dispatcherType); } finally { servletRequestContext.setDispatcherType(oldDispatch); servletRequestContext.setCurrentServlet(oldChain); } }
@Override public ServletRequestContext run() { return ServletRequestContext.current(); } };
private void handleError(final Throwable t) { try { servletRequestContext.getCurrentServletContext().invokeRunnable(servletRequestContext.getExchange(), new Runnable() { @Override public void run() { listener.onError(t); } }); } finally { IoUtils.safeClose(channel, servletRequestContext.getExchange().getConnection()); if (pooledBuffer != null) { pooledBuffer.close(); pooledBuffer = null; buffer = null; } } } }