Apache/Tomcat error - wrong pages being delivered - apache

This error has been driving me nuts. We have a server running Apache and Tomcat, serving multiple different sites. Normally the server runs fine, but sometimes an error happens where people are served the wrong page - the page that somebody else requested!
Clues:
The pages being delivered are those that another user requested recently, and are otherwise delivered correctly. It's been known for two simultaneous requests to be swapped. As far as I can tell, none of the pages being incorrectly delivered are older than a few minutes.
It only affects the files that are being served by Tomcat. Static files like images are unaffected.
It doesn't happen all the time. When it does happen, it happens for everybody.
It seems to happen at times of peak demand. However, the demand is not yet very high - it's certainly well within the bounds of what Apache can cope with.
Restarting Tomcat fixed it, but only for a few minutes. Restarting Apache fixed it, but only for a few minutes.
The server is running Apache 2 and Tomcat 6, using a Java 6 VM on Gentoo. The connection is with AJP13, and JkMount directives within <VirtualHost> blocks are correct.
There's nothing of use in any of the log files.
Further information:
Apache does not have any form of caching turned on. All the caching-related entries in httpd.conf and related imports say, for example:
<IfDefine CACHE>
LoadModule cache_module modules/mod_cache.so
</IfDefine>
While the options for Apache don't include that flag:
APACHE2_OPTS="-D DEFAULT_VHOST -D INFO -D LANGUAGE -D SSL -D SSL_DEFAULT_VHOST -D PHP5 -D JK"
Tomcat likewise has no caching options switched on, that I can find.
toolkit's suggestion was good, but not appropriate in this case. What leads me to believe that the error can't be within my own code is that it isn't simply a few values that are being transferred - it's the entire request, including the URL, parameters, session cookies, the whole thing. People are getting pages back saying "You are logged in as John", when they clearly aren't.
Update:
Based on suggestions from several people, I'm going to add the following HTTP headers to Tomcat-served pages to disable all forms of caching:
Cache-Control: no-store
Vary: *
Hopefully these headers will be respected not just by Apache, but also by any other caches or proxies that may be in the way. Unfortunately I have no way of deliberately reproducing this error, so I'm just going to have to wait and see if it turns up again.
I notice that the following headers are being included - could they be related in any way?
Connection: Keep-Alive
Keep-Alive: timeout=5, max=66
Update:
Apparently this happened again while I was asleep, but has stopped happening now I'm awake to see it. Again, there's nothing useful in the logs that I can see, so I have no clues to what was actually happening or how to prevent it.
Is there any extra information I can put in Apache or Tomcat's logs to make this easier to diagnose?
Update:
Since this has happened again a couple of times, we've changed how Apache connects to Tomcat to see if it affects things. We were using mod_jk with a directive like this:
JkMount /portal ajp13
We've switched now to using mod_proxy_ajp, like so:
ProxyPass /portal ajp://localhost:8009/portal
We'll see if it makes any difference. This error was always annoyingly unpredictable, so we can never definitively say if it's worked or not.
Update:
We just got the error briefly on a site that was left using mod_jk, while a sister site on the same server using mod_proxy_ajp didn't show the error. This doesn't prove anything, but it does provide evidence that swithing to mod_proxy_ajp may have helped.
Update:
We just got the error again last night on a site using mod_proxy_ajp, so clearly that hasn't solved it - mod_jk wasn't the source of the problem. I'm going to try the anonymous suggestion of turning off persistent connections:
KeepAlive Off
If that fails as well, I'm going to be desperate enough to start investigating GlassFish.
Update:
Dammit! The problem just came back. I hadn't seen it in a while, so I was starting to think we'd finally sorted it. I hate heisenbugs.

Could it be the thread-safety of your servlets?
Do your servlets store any information in instance members.
For example, something as simple as the following may cause thread-related issues:
public class MyServlet ... {
private String action;
public void doGet(...) {
action = request.getParameter("action");
processAction(response);
}
public void processAction(...) {
if (action.equals("foo")) {
// send foo page
} else if (action.equals("bar")) {
// send bar page
}
}
}
Because the serlvet is accessed by multiple threads, there is no guarantee that the action instance member will not be clobbered by someone elses request, and end up sending the wrong page back.
The simple solution to this issue is to use local variables insead of instance members:
public class MyServlet ... {
public void doGet(...) {
String action = request.getParameter("action");
processAction(action, response);
}
public void processAction(...) {
if (action.equals("foo")) {
// send foo page
} else if (action.equals("bar")) {
// send bar page
}
}
}
Note: this extends to JavaServer Pages too, if you were dispatching to them for your views?

Check if your headers allow caching without the correct Vary HTTP header (if you use session cookies, for instance, and allow caching, you need an entry in the Vary HTTP header for the cookie header, or a cache/proxy might serve the cached version of a page intended for one user to another user).
The problem might be not with caching on your web server, but on another layer of caching (either on a reverse proxy in front of your web server, or on a proxy near the users). If the clients are behing a NAT, they might also be behind a transparent proxy (and, to make things even harder to debug, the transparent proxy might be configured to not be visible in the headers).

8 updates of the question later one more issue to use to test/reproduce, albeit it might be difficult (or expensive) for public sites.
You could enable https on the sites. This would at least wipe out any other proxies caches along the way. It'd be bad to see that there are some forgotten loadbalancers or company caches on the way that interfere with your traffic.
For public sites this would imply trusted certificates on the keys, so some money will be involved. For testing self-signed keys might suffice. Also, check that there's no transparent proxy involved that decrypts and reencrypts the traffic. (they are easily detectable, as they can't use the same certificate/key as the original server)

Although you did mention mod_cache was not enabled in your setup, for others who may have encountered the same issue with mod_cache enabled (even on static contents), the solution is to make sure the following directive is enabled on the Set-Cookie HTTP header:
CacheIgnoreHeaders Set-Cookie
The reason being mod_cache will cache the Set-Cookie header that may get served to other users. This would then leak session ID from the user who last filled the cache to another.

I had this problem and it really drove me nuts. I dont know why, but I solved it turning off the Keep Alive on the http.conf
from
KeepAlive On
to
KeepAlive Off
My application doesn't use the keepalive feature, so it worked very well for me.

Try this:
response.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
response.setHeader("Pragma", "no-cache"); //HTTP 1.0
response.setDateHeader("Expires", 0); //prevents caching at the proxy server

Have a look at this site, it describes an issue with mod_jk. I came accross your posting while looking at a very similar issue. Basically the fix is to upgrade to a newer version of mod_jk. I haven't had a chance to implement the change in our server yet, but I'm going to try this tomorrow and see if it helps.
http://securitytracker.com/alerts/2009/Apr/1022001.html

I'm no expert, but could it be some weird Network Address Translation issue?

We switched Apache from proxying with AJP to proxying with HTTP. So far it appears to have solved the issue, or at least vastly reduced it - the problem hasn't been reported in months, and the app's use has increased since then.
The change is in Apache's httpd.conf. Having started with mod_jk:
JkMount /portal ajp13
We switched to mod_proxy_ajp:
ProxyPass /portal ajp://localhost:8009/portal
Then finally to straight mod_proxy:
ProxyPass /portal http://localhost:8080/portal
You'll need to make sure Tomcat is set up to serve HTTP on port 8080. And remember that if you're serving /, you need to include / on both sides of the proxy or it starts crying:
ProxyPass / http://localhost:8080/

It may be not a caching issue at all. Try to increase MaxClients parameter in apache2.conf. If it is too low (150 by default?), Apache starts to queue requests. When it decides to serve queued request via mod_proxy it pulls out a wrong page (or may be it is just stressed doing all the queuing).

Are you sure that is the page that somebody else requested or a page without parameters?,
you could get weird errors if your connectionTimeout is too short at server.xml on the tomcat server behind apache, increase it to a bigger number:
default configuration:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
changed:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="2000000"
redirectPort="8443" />

Related

Mod_jk and Tomcat stuck at Sending Reply

Currently, the server at work is underperforming and the way it's set up is not ideal either. For this reason I'm trying to find a new way to do things that will hopefully help with both, performance and deployment.
The approach I decided for is to have tomcat instances for our webapps (currently there are two, so it'd be an instance per webapp) and use Apache as a "front". I'm not experienced in this, so It's normal I'm having issues here and there, but so far I've manage to get this going.
What I expect is to redirect from mysite.com index page to either mysite.com/service1 or mysite.com/service2. Service1 was setup in out test server at port 8080 and service2 at 8081. I installed Apache2 and mod_jk yesterday and set up apache with the contents of mysite.com. Today I started the configurations, that ended up as follow:
workers.properties
worker.list=s1
worker.s1.type=ajp13
worker.s1.port=8009
#host is localhost by default according to the documentation
jk.load
LoadModule jk_module /usr/lib/apache2/modules/mod_jk.so
JkWorkersFile /etc/apache2/workers.properties
JkLogFile /var/log/apache2/mod_jk.log
JkLogLevel debug
JkMount /service1/* s1
Service1's server.xml connector (The rest is all default)
<Connector protocol="AJP/1.3" port="8009" redirectPort="8443" />
I had more, but because of the errors, I took a step back and tried with only one tomcat for now. I will add the second tomcat and a loadbalancer.
Ok, so what's going on?
I can access the server and the index page of our system with no problem. The problem is when I try to redirect to service1. It just loads without response, but if I try to access service1 directly by port 8080, it works properly (I tired commenting out this connector. No luck).
Looking at server-status, I see the request stuck at w/sending reply, and in mod_jk.log I see that the worker properly matches the request. So while my configurations seem to be right, there is something in between happening. I don't really know if it's something with Apache, Tomcat or Mod_jk. I also tried to follow several guides of how to do this, but all of them got me to 404s. Looking around here and ServerFault didn't shed much light unfortunately so I'm the one asking now.
Am I missing something? Should I just use another approach? I'm very new at this and I'm at loss right now. The configuration and the logs show that nothing is really wrong (at first glance, at least...) so I'm entirely sure if my case scneario is even posible with mod_jk... HOnestly to run it back and try with proxy is very tempting at this point, but if I am, I'd rather know where Im wrong.
Additional info: Running on Ubuntu Server 18.04, lastest apache2 and mod_jk avaliable from apt (as of Apr 14), java 1.8 and Tomcat 8.5.64.
There was a change in Tomcat last year (from version 8.5.51 and version 9.0.31), which introduced a secretRequired attribute to the AJP connector with a default of true (cf. documentation). Hence you can either:
add a shared secret between the AJP connector and mod_jk
or add secretRequired="false" to the AJP connector:
<Connector protocol="AJP/1.3" port="8009" secretRequired="false" redirectPort="8443" />
Remark: AJP is a very old protocol and rarely used. Since your installation is pretty new, you might consider using directly HTTP (cf. this talk).

Forwarded Tomcat through Apache uses wrong Context path

Okay let me explain my problem really fast. I have a JEE Programm running on my tomcat server. The server has some user defined in the tomcat-users.xml When i test my programm on my local machine everything works fine.
However if i deploy the .war on my server and i want to access a Rest Endpoint i get a 401 unauthorized error. If i remove the users security check i can work fine with the program. So the URLs and server setup is correct.
I think that the problem is somehow related to the forwarding of tomcat through my apache.
So lets assume i have an apache running on http://myIp.de
then i forwarded tomcat with following apache config:
ProxyRequests off
ProxyPass /tomcat http://localhost:8181/ nocanon
ProxyPassReverse /tomcat http://localhost:8181/
so now i can reach tomcat through: http://myIp.de/tomcat
also i can "speak" to my app via: tomcat/myApp
But somehow the Authentizication now fails. And i think the problem is
somehow related to wrong context path. Because tomcat/manager
also fails to login.
Make your life easier by deploying your app under /tomcat on tomcat too. This way there's no path-translation required. Keep in mind that you'll get all the session cookies tied to a specific path and this path is not necessarily translated once forwarded to the client.
Also, sooner or later you might need
ProxyPreserveHost On
(look it up) or utilize mod_jk to preserve this header (and more information) automatically.
Edit: Following your comment, Basic Auth headers seem not to be forwarded to tomcat as well. I haven't attempted this myself, but all the places that I've looked up seem to imply that there'd be some duplication (e.g. second credentials file for Apache) - that doesn't look good. In this case I'd suggest to try out mod_jk rather than mod_proxy. You'll use the JkMount directive, rather than ProxyPass and need a workers.properties, but mod_jk is a lot better in keeping the full context of the request when forwarding to tomcat. I've had good experience with it so far and have only heard little complaints about it - largely in situations that were pretty huge and complex/complicated anyway. At least you should try if it solves your problems.

What is yourinfo.allrequestsallowed.net?

In my apache instillation, I keep seeing the following line in my access logs:
"POST http://yourinfo.allrequestsallowed.net/ HTTP/1.1" 200
It's really freaking me out because this site is not being hosted on my server (I checked the IP just to be 100% sure). I added a "Deny all" line since the site is still in development, and now the HTTP 200 response changed to 403, like the domain is being hosted on my server.
I'm incredibly confused and scared. Does anybody know what's going on? Can I Deny all to this domain that's apparently pointing to my server?
You may want to check to make sure you don't have ProxyRequests On set anywhere where it's not supposed to. Typically a request like that is for a forward proxy and the troubling bit is that you returned a 200 response which could indicate that the request was successfully proxied.
Take a look at this wiki page about Proxy abuse.
My server is properly configured not to proxy, so why is Apache returning a 200 (Success) status code?
That status code indicates that Apache successfully sent a response to the client, but not necessarily that the response was retrieved from the foreign website.
RFC2616 section 5.1.2 mandates that Apache must accept requests with absolute URLs in the request-URI, even for non-proxy requests. This means that even when proxying is turned off, Apache will accept requests that look like proxy requests. But instead of retrieving the content from the foreign site, Apache will serve the content at the corresponding location on your website. Since the hostname probably doesn't match a name for your site, Apache will look for the content on your default host.
But it's probably worthwhile to check that you aren't proxying. Otherwise, it's not really that big of a deal.
After Jon Lin pointed me in the right direction, I figured it out.
After disabling mod_proxy and enabling mod_security, I added the following to my virtual host configuration:
SecRuleEngine On
SecRule REQUEST_LINE "://" drop,phase:1
And then restarted apache. It quits the connection and returns any amount of data, which uses less resources and bandwidth during Brute Force and DDOS attacks.
Also, it shows as an HTTP 404 Response in the access logs.
EDIT: I updated the rule to drop all types or proxies (https,https,ftp). I don't know how many protocols can be used this way, but I'd rather be safe than sorry.

Bad gateways with large POST uploads and my apache + varnish + plone setup

This is a rather complicated scenario, so I would highly appreciate any pointer to the correct direction.
So I have setup apache on server A to proxy https traffic το server B, that is a plone site behind varnish and apache.
I connect to A and can browse the site on https, everything is fine. However, problems start when I upload files, via plone's POST forms. I can upload small files (~1 MB), but when I try to upload a 50MB file, I wait all the time till the file is uploaded, and when the indication is 100%, I get a Bad gateway (The proxy server received an invalid response from an upstream server.)
It seems to me that something timeouts between the communication of A and B and instead of being redirected to the correct url, I get a Bad gateway, not to mention that the file is not uploaded.
On the apache log I see
[error] proxy: pass request body failed
As suggested on other threads, I've experimented with the following values with no luck
force-proxy-request-1.0
proxy-nokeepalive
KeepAlive
KeepAliveTimeout
proxy-initial-not-pooled
Timeout
ProxyTimeout
Sooooo..any suggestions? Thanks a million in advance!
Did you check the varnish configuration? varnish has some timeouts of its own, I am familiar with send_timeout which usually breaks downloads if they fail to finish within a few seconds (Varnish really isn't any good for large downloads, because you end doing stupid things like configuring send_timeout=7200 to make it work).
Also, set first_byte_timeout to a larger number for that backend, because a large file upload might delay plone's response just enough to cause this.
Setting the Timeout and KeepAliveTimeout in the apache virtual host file worked for me.
Example:
Timeout 3600
KeepAliveTimeout 50

JSJaC+Openfire works only local

so far I developed completey locally, having everything (Apache, Openfire, JSJaC application) on my laptop, running quite fine. Now I want to use remote server for Apache/Openfire. I did basically the same steps, incl. the whole http-bind stuff. I test the setting with simpleclient.html provided by JSJaC.
Now here's the deal, if I use the simpleclient directly on the remote server - e.g., http://here.domain.org/simpleclient.html - it works. If I use it locally - e.g., http://[local_machine]/simpleclient.html - and with the same settings I get an 503 (service unavailable). It seems to be more a network/Apache issue than Openfire/JSJaC one, but I'm not an expert.
My parameters for the simpleclient:
HTTP Base: http://here.domain.org/http-bind/
JabberServer: here.domain.org
So in my apache virtual host conf file I have the lines:
AddDefaultCharset UTF-8
ProxyReqests On
ProxyPass /http-bind/ http://127.0.0.1:7070/http-bind/
So basically the http bind works since I can connect when the simpleclient.html resides on the server. What I tried so far:
checked if 7070 open from extern: yes
checked etc/hosts - here the relevant lines
127.0.0.1 localhost
123.123.123.123 here.domain.org here
checked Apache conf for restrictions: can't find any, basically i have an "Allow from all" everywhere (but I'm not completely sure where to look at)
By the way, with,e.g., Pidgin I can connect from my laptop to the remote server. Just the JSJaC simpleclient won't do. So I assume it's the http-bind that causes the trouble. I would understand if port 7070 weren't open, but it is.
Any hints or help are much appreciated!
Christian
Ok, I got it. It was a cross-domain scripting issue. I started looking into the JSJaC library and noticed that it makes XmlHttpRequests which by default won't work across different domains. I therefore had to allow this with Apache on the Openfire-Server. I added the follwing entries in the VirtualHost conf file:
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Methods "POST, GET, OPTIIONS"
Header always set Access-Control-Allow-Credentials true
Header always set Access-Control-Allow-Headers "Content-Type, *"
Of course the mod_headers module must be loaded for this.
I'm not sure which entries are actually required, I didn't try every combinations. I think the always is needed since the request to the http-bind address is a proxy thingy.