Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cookie path bug #227

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 106 additions & 14 deletions src/main/java/org/mitre/dsmiley/httpproxy/ProxyServlet.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import org.apache.http.client.methods.AbortableHttpRequest;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.config.SocketConfig;
import org.apache.http.cookie.SM;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
Expand All @@ -46,11 +47,11 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.net.HttpCookie;
import java.net.URI;
import java.util.BitSet;
import java.util.Enumeration;
import java.util.Formatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
* An HTTP reverse proxy/gateway servlet. It is designed to be extended for customization
Expand Down Expand Up @@ -84,6 +85,9 @@ public class ProxyServlet extends HttpServlet {
/** A boolean parameter name to keep COOKIES as-is */
public static final String P_PRESERVECOOKIES = "preserveCookies";

/** A boolean parameter name to cache root path cookies **/
public static final String P_CACHEROOTPATHCOOKIES = "cacheRootPathCookies";

/** A boolean parameter name to have auto-handle redirects */
public static final String P_HANDLEREDIRECTS = "http.protocol.handle-redirects"; // ClientPNames.HANDLE_REDIRECTS

Expand Down Expand Up @@ -113,6 +117,9 @@ public class ProxyServlet extends HttpServlet {
protected static final String ATTR_TARGET_HOST =
ProxyServlet.class.getSimpleName() + ".targetHost";

/**default root path of cookie**/
private static String COOKIE_ROOT_PATH = "/";

/* MISC */

protected boolean doLog = false;
Expand All @@ -121,6 +128,8 @@ public class ProxyServlet extends HttpServlet {
protected boolean doSendUrlFragment = true;
protected boolean doPreserveHost = false;
protected boolean doPreserveCookies = false;
/**Whether to enable cache session cookies, The default value is invalid**/
protected boolean doCacheRootPathCookies = false;
protected boolean doHandleRedirects = false;
protected boolean useSystemProperties = true;
protected boolean doHandleCompression = false;
Expand All @@ -137,6 +146,9 @@ public class ProxyServlet extends HttpServlet {
protected HttpHost targetHost;//URIUtils.extractHost(targetUriObj);

private HttpClient proxyClient;
/**Caches proxy cookies corresponding to the current ssession , If the current session is invalid (session timeout), or the JVM's fullGC chooses to clear the SoftReference data,
* Use the SoftReference function to clear the cookies of an expired session. Avoid memory leaks caused by caching when memory is running low **/
private static volatile Map<String, SoftReference<Set<HttpCookie>>> rootPathCookies = new ConcurrentHashMap<>();// key: sessionId, value: proxyCookies

@Override
public String getServletInfo() {
Expand Down Expand Up @@ -182,6 +194,11 @@ public void init() throws ServletException {
this.doPreserveCookies = Boolean.parseBoolean(preserveCookiesString);
}

String cacheRootPathCookies = getConfigParam(P_CACHEROOTPATHCOOKIES);
if (cacheRootPathCookies != null) {
this.doCacheRootPathCookies = Boolean.parseBoolean(cacheRootPathCookies);
}

String handleRedirectsString = getConfigParam(P_HANDLEREDIRECTS);
if (handleRedirectsString != null) {
this.doHandleRedirects = Boolean.parseBoolean(handleRedirectsString);
Expand Down Expand Up @@ -269,8 +286,8 @@ protected void initTarget() throws ServletException {
*/
protected HttpClient createHttpClient() {
HttpClientBuilder clientBuilder = getHttpClientBuilder()
.setDefaultRequestConfig(buildRequestConfig())
.setDefaultSocketConfig(buildSocketConfig());
.setDefaultRequestConfig(buildRequestConfig())
.setDefaultSocketConfig(buildSocketConfig());

clientBuilder.setMaxConnTotal(maxConnections);
clientBuilder.setMaxConnPerRoute(maxConnections);
Expand Down Expand Up @@ -332,7 +349,7 @@ public void destroy() {

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
throws ServletException, IOException {
throws ServletException, IOException {
//initialize request attributes from caches if unset by a subclass by this point
if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
Expand All @@ -348,7 +365,7 @@ protected void service(HttpServletRequest servletRequest, HttpServletResponse se
HttpRequest proxyRequest;
//spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null ||
servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
proxyRequest = newProxyRequestWithEntity(method, proxyRequestUri, servletRequest);
} else {
proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
Expand Down Expand Up @@ -430,7 +447,7 @@ protected HttpResponse doExecute(HttpServletRequest servletRequest, HttpServletR
}

protected HttpRequest newProxyRequestWithEntity(String method, String proxyRequestUri,
HttpServletRequest servletRequest)
HttpServletRequest servletRequest)
throws IOException {
HttpEntityEnclosingRequest eProxyRequest =
new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
Expand Down Expand Up @@ -467,8 +484,8 @@ protected void closeQuietly(Closeable closeable) {
static {
hopByHopHeaders = new HeaderGroup();
String[] headers = new String[] {
"Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization",
"TE", "Trailers", "Transfer-Encoding", "Upgrade" };
"Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization",
"TE", "Trailers", "Transfer-Encoding", "Upgrade" };
for (String header : headers) {
hopByHopHeaders.addHeader(new BasicHeader(header, null));
}
Expand Down Expand Up @@ -519,6 +536,41 @@ protected void copyRequestHeader(HttpServletRequest servletRequest, HttpRequest
} else if (!doPreserveCookies && headerName.equalsIgnoreCase(org.apache.http.cookie.SM.COOKIE)) {
headerValue = getRealCookie(headerValue);
}
if(doCacheRootPathCookies){
addRootPathCookies(servletRequest, proxyRequest, headerName, headerValue);
}else {
proxyRequest.addHeader(headerName, headerValue);
}
}
}

/**
* Add root path cookies
* @param servletRequest
* @param proxyRequest
* @param headerName
* @param headerValue
*/
private void addRootPathCookies(HttpServletRequest servletRequest, HttpRequest proxyRequest, String headerName, String headerValue) {
if(SM.COOKIE.equalsIgnoreCase(headerName) || SM.COOKIE2.equalsIgnoreCase(headerName)){
String finalHeaderValue = null;
String sessionId = servletRequest.getSession().getId();
SoftReference<Set<HttpCookie>> setSoftReference = rootPathCookies.get(sessionId);
javaofferss marked this conversation as resolved.
Show resolved Hide resolved
Set<HttpCookie> proxyCookies = null;
if(setSoftReference != null && (proxyCookies = setSoftReference.get()) != null){
StringBuilder cookieBuilder = new StringBuilder(headerValue);//Cookies in the current request
for(HttpCookie proxyCookie : proxyCookies){
if(!cookieBuilder.toString().contains(proxyCookie.toString())){
if(cookieBuilder.length()!=0){
cookieBuilder.append("; ");
}
cookieBuilder.append(proxyCookie.toString()); //Append cached root path cookies
}
}
finalHeaderValue = cookieBuilder.toString();
}
proxyRequest.addHeader(headerName,finalHeaderValue);
}else{
proxyRequest.addHeader(headerName, headerValue);
}
}
Expand Down Expand Up @@ -552,7 +604,7 @@ protected void copyResponseHeaders(HttpResponse proxyResponse, HttpServletReques
* This is easily overwritten to filter out certain headers if desired.
*/
protected void copyResponseHeader(HttpServletRequest servletRequest,
HttpServletResponse servletResponse, Header header) {
HttpServletResponse servletResponse, Header header) {
String headerName = header.getName();
if (hopByHopHeaders.containsHeader(headerName))
return;
Expand Down Expand Up @@ -590,16 +642,56 @@ protected void copyProxyCookie(HttpServletRequest servletRequest,
protected Cookie createProxyCookie(HttpServletRequest servletRequest, HttpCookie cookie) {
String proxyCookieName = getProxyCookieName(cookie);
Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
servletCookie.setPath(buildProxyCookiePath(servletRequest)); //set to the path of the proxy servlet
//set to the path of the proxy servlet
String proxyCookiePath = buildProxyCookiePath(servletRequest);
servletCookie.setPath(proxyCookiePath);
servletCookie.setComment(cookie.getComment());
servletCookie.setMaxAge((int) cookie.getMaxAge());
// don't set cookie domain
servletCookie.setSecure(cookie.getSecure());
servletCookie.setVersion(cookie.getVersion());
servletCookie.setHttpOnly(cookie.isHttpOnly());
if(doCacheRootPathCookies){
cacheRootPathCookies(servletRequest, cookie);
}
return servletCookie;
}

/**
* cache root path cookies
* @param servletRequest
* @param cookie
*/
private void cacheRootPathCookies(HttpServletRequest servletRequest, HttpCookie cookie) {
if(COOKIE_ROOT_PATH.equals(cookie.getPath())){
String sessionId = servletRequest.getSession().getId();
SoftReference<Set<HttpCookie>> reference = rootPathCookies.get(sessionId);
List<String> expiredKey = new LinkedList<>();
if(reference == null || reference.get() == null){
//Facilitate the data that has been cleaned by FULLGC at a time, and remove the expired data
rootPathCookies.forEach((k,v)->{
if(v.get() == null){
expiredKey.add(k);
}
});
for(String ek : expiredKey){
rootPathCookies.remove(ek);
}

synchronized (servletRequest.getSession()){
if((reference = rootPathCookies.get(sessionId)) == null || reference.get() == null){
Set<HttpCookie> httpCookiesSet = new HashSet<>();
reference = new SoftReference<Set<HttpCookie>>(httpCookiesSet);
rootPathCookies.put(sessionId,reference) ;
}
}
}
if(reference.get() != null){
reference.get().add(cookie);
}
}
}

/**
* Set cookie name prefixed with a proxy value so it won't collide with other cookies.
*
Expand All @@ -621,7 +713,7 @@ protected String buildProxyCookiePath(HttpServletRequest servletRequest) {
String path = servletRequest.getContextPath(); // path starts with / or is empty string
path += servletRequest.getServletPath(); // servlet path starts with / or is empty string
if (path.isEmpty()) {
path = "/";
path = COOKIE_ROOT_PATH;
}
return path;
}
Expand Down Expand Up @@ -680,7 +772,7 @@ protected void copyResponseEntity(HttpResponse proxyResponse, HttpServletRespons
* but may read or skip fewer bytes.
*
* To work around this, a flush is issued always if compression
* is handled by apache http client
* is handled by apache http client
*/
if (doHandleCompression || is.available() == 0 /* next is.read will block */) {
os.flush();
Expand Down