Apache Tomcat 5.X HTTPS server configuration not receiving POST request data - servlets

I am facing a Tomcat Server configuration problem.
I have requested a certificate from GoDaddy and have configured the same with Apache Tomcat 5.x. Following is the snippet from tomcat5.x\conf\server.xml for HTTPS configuration.
<Connector port="8443" maxHttpHeaderSize="8192" protocol="HTTP/1.1"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" disableUploadTimeout="true"
acceptCount="100" scheme="https" secure="true"
keystoreFile="/path/to/tomcat.keystore" keystorePass="xxxxxxxxx"
clientAuth="false" sslProtocol="TLS" SSLEnabled="false"/>
I am able to access the Servlet deployed on my server using https://www.exampleserver.com:8443/servletname successfully
Now I am trying HTTP POST request with JSON data in HTTP Body to the same Servlet and I am trying to log the POST data in the servlet but the POST data is empty or not available.
The following is the code snippet to Log POST data in doPost method of Servlet
// Respond with OK and status 200 in a timely fashion to prevent redelivery
response.setContentType("text/html");
Writer writer = response.getWriter();
writer.append("OK");
writer.close();
// Get the notification object from the request body (into a string so we
// can log it)
BufferedReader notificationReader =
new BufferedReader(new InputStreamReader(request.getInputStream()));
String notificationString = "";
// Count the lines as a very basic way to prevent Denial of Service attacks
int lines = 0;
while (notificationReader.ready()) {
notificationString += notificationReader.readLine();
lines++;
// No notification would ever be this long. Something is very wrong.
if (lines > 1000) {
throw new IOException("Attempted to parse notification payload that was unexpectedly long.");
}
}
LOG.info("got raw notification " + notificationString);
The Log.info statement always prints "got raw notification " which means no data was available.
Previous
Interesting part is it works when the Servlet is deployed or accesses using HTTP not HTTPS
Update
I tried curl (JSON data) to the same Servlet with HTTP as well as HTTPS but it's NOT working for both. On Local server it's working.
To be honest I don't have much experience in configuring Apache Tomcat Server and SSL certificates. I followed the configuration steps provided by GoDaddy and of course with the help of Google.

Related

Passing hostname to Invoke-WebRequest to warm up web application

I'm trying to generate requests to fire at our new versions of our .net web apps in IIS in order to start the app pools and warm them up.
The different versions are bound to local IPs and I'm trying to hit them with the following request as it looks like it will do the job:
Invoke-WebRequest 'http://172.28.36.31' -Headers #{host="www.mydomain.com"}
Now got the above working.
Any ideas on getting the same request to work over https and ignore and self signed cert warnings? There's a couple of options to ignore the warnings but haven't seen anything to use an ip with a custom host (akin to a local host entry)
You are getting a non-success http status code from the server which makes PowerShell throw an exception. Based on the "Object moved to here" message I assume it's going to be a redirect response.
You can check the status code by modifying your call like this:
try {
$response = Invoke-WebRequest 'http://172.28.36.31' -Headers #{host="www.mydomain.com"}
} catch {
$_.Exception.Response.StatusCode.Value__
}

AspNet.Security.OpenIdConnect.Server (ASP.NET vNext) Authority Configuration in Mixed http/https Environments

I am using Visual Studio 2015 Enterprise and ASP.NET vNext Beta8 to build an endpoint that both issues and consumes JWT tokens as described in detail here. As explained in that article the endpoint uses AspNet.Security.OpenIdConnect.Server (AKA OIDC) to do the heavy lifting.
While standing this prototype up in our internal development environment we have encountered a problem using it with a load balancer. In particular, we think it has to do with the "Authority" setting on app.UseJwtBearerAuthentication and our peculiar mix of http/https. With our load balanced environment, any attempt to call a REST method using the token yields this exception:
WebException: The remote name could not be resolved: 'devapi.contoso.com.well-known'
HttpRequestException: An error occurred while sending the request.
IOException: IDX10804: Unable to retrieve document from: 'https://devapi.contoso.com.well-known/openid-configuration'.
Consider the following steps to reproduce (this is for prototyping and should not be considered production worthy):
We created a beta8 prototype using OIDC as described here.
We deployed the project to 2 identically configured IIS 8.5 servers running on Server 2012 R2. The IIS servers host a beta8 site called "API" with bindings to port 80 and 443 for the host name "devapi.contoso.com" (sanitized for purposes of this post) on all available IP addresses.
Both IIS servers have a host entry that point to themselves:
127.0.0.1 devapi.contoso.com
Our network admin has bound a * certificate (*.contoso.com) with our Kemp load balancer and configured the DNS entry for https://devapi.contoso.com to resolve to the load balancer.
Now this is important, the load balancer has also been configured to proxy https traffic to the IIS servers using http (not, repeat, not on https). It has been explained to me that this is standard operating procedure for our company because they only have to install the certificate in one place. We're not sure why our network admin bound 443 in IIS since it, in theory, never receives any traffic on this port.
We make a secure post via https to https://devapi.contoso.com/authorize/v1 to fetch a token, which works fine (the details of how to make this post are here ):
{
"sub": "todo",
"iss": "https://devapi.contoso.com/",
"aud": "https://devapi.contoso.com/",
"exp": 1446158373,
"nbf": 1446154773
}
We then use this token in another secure get via https to https://devapi.contoso.com/values/v1/5.
OpenIdConnect.OpenIdConnectConfigurationRetriever throws the exception:
WebException: The remote name could not be resolved: 'devapi.contoso.com.well-known'
HttpRequestException: An error occurred while sending the request.
IOException: IDX10804: Unable to retrieve document from: 'https://devapi.contoso.com.well-known/openid-configuration'.
We think this is happening because OIDC is attempting to consult the host specified in "options.Authority", which we set at startup time to https://devapi.contoso.com/. Further we speculate that because our environment has been configured to translate https traffic to non https traffic between the load balancer and IIS something is going wrong when the framework tries to resolve https://devapi.contoso.com/. We have tried many configuration changes including even pointing the authority to non-secure http://devapi.contoso.com to no avail.
Any assistance in helping us understand this problem would be greatly appreciated.
#Pinpoint was right. This exception was caused by the OIDC configuration code path that allows IdentityModel to initiate non-HTTPS calls. In particular the code sample we were using was sensitive to missing trailing slash in the authority URI. Here is a code fragment that uses the Uri class to combine paths in a reliable way, regardless of whether the Authority URI has a trailing slash:
public void Configure(IApplicationBuilder app, IOptions<AppSettings> appSettings)
{
.
.
.
// Add a new middleware validating access tokens issued by the OIDC server.
app.UseJwtBearerAuthentication
(
options =>
{
options.AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme ;
options.AutomaticAuthentication = false ;
options.Authority = new Uri(appSettings.Value.AuthAuthority).ToString() ;
options.Audience = new Uri(appSettings.Value.AuthAuthority).ToString() ;
// Allow IdentityModel to use HTTP
options.ConfigurationManager =
new ConfigurationManager<OpenIdConnectConfiguration>
(
metadataAddress : new Uri(new Uri(options.Authority), ".well-known/openid-configuration").ToString(),
configRetriever : new OpenIdConnectConfigurationRetriever() ,
docRetriever : new HttpDocumentRetriever { RequireHttps = false }
);
}
);
.
.
.
}
In this example we're pulling in the Authority URI from config.json via "appSettings.Value.AuthAuthority" and then sanitizing/combining it using the Uri class.

Mule ESB synchronous Until Successful payload modification

I've spent hours trying to solve my problem which seems to be caused by synchronous Until Successful Scope in Mule ESB v3.5.0. It seems to modify message payload when sending an outbound HTTP requests.
I need to continue in my flow after outbound HTTP request successfully returns from a HTTP server (which sometimes has connection problems). Thus I need the sync variant of Until Successful. For now I use just a simple Logger after the Until Successful block.
The body of my HTTP request is a XML file. When there is no problem at my server and the Until Successful doesn't need to make another HTTP request again, I receive the XML which I sent.
However, when there is a connectivity problem so the Until Successful repeats requesting a few times and then the server goes back online, on my server I receive an instance of org.apache.commons.httpclient.methods.PostMethod instead of the sent XML in the request body!
So no more XML on my server. It seems this sync Until Successful simply discards the original message payload...
The standard async variant of Until Successful works as intended - getting XML in requests all the time.
Here is a minimal sample of HTTP outbound endpoint with Until Successful:
<flow name="perform" doc:name="performHTTP">
<until-successful maxRetries="${repeater.retries}" millisBetweenRetries="${repeater.period}" failureExpression="#[exception != null && (exception.causedBy(java.net.ConnectException) || exception.causedBy(java.net.SocketTimeoutException)) || message.inboundProperties['http.status'] != 200]" doc:name="Until Successful - Repeater" synchronous="true">
<http:outbound-endpoint exchange-pattern="request-response" host="${https.outbound.address}" port="${https.outbound.port}" path="${https.outbound.path}" method="POST" mimeType="text/xml" transformer-refs="Custom_Outbound_HTTPS_Header" contentType="text/xml" doc:name="HTTPS - Outbound" doc:description="Outcoming HTTPS connection" responseTimeout="15000"/>
</until-successful>
<logger message="#['Sending done']" level="INFO" doc:name="Logger - Done"/>
</flow>
Long story short:
synchronous Until Successful: XML -> HTTP request - { NET } - HTTP request -> org.apache.commons.httpclient.methods.PostMethod
asynchronous Until Successful: XML -> HTTP request - { NET } - HTTP request -> XML
I had the same problem and fixed it by saving my payload and retrieving on each retry something like this
<set-variable value="#[payload]" variableName="paloadbeforecall" doc:name="Variable" />
<until-successful maxRetries="${repeater.retries}" millisBetweenRetries="${repeater.period}" failureExpression="#[exception != null && (exception.causedBy(java.net.ConnectException) || exception.causedBy(java.net.SocketTimeoutException)) || message.inboundProperties['http.status'] != 200]" doc:name="Until Successful - Repeater" synchronous="true">
<processor-chain>
<set-payload value="#[flowVars.?paloadbeforecall]" doc:name="Variable" />
<http:outbound-endpoint exchange-pattern="request-response" host="${https.outbound.address}" port="${https.outbound.port}" path="${https.outbound.path}" method="POST" mimeType="text/xml" transformer-refs="Custom_Outbound_HTTPS_Header" contentType="text/xml" doc:name="HTTPS - Outbound" doc:description="Outcoming HTTPS connection" responseTimeout="15000"/>
</processor-chain>
</until-successful>
Sounds like a bug. It would be interesting to report this as an issue. Anyhow, there is a simple workaround for this, just wrap the until-successful in a wire-tap. This will create a copy of the message (not necessarily the payload) and given that the payload is inmmutable (String) the oubound-endpoint will just change the reference without affecting the flow after the wire-tap.

Netty - sending http requests over ssl

I'm trying to get a client/server program exchanging http messages over ssl. To start, I created client and server programs that successfully exchange http requests using DefaultHttpRequest. The code that sends the request looks something like this:
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "https://localhost:8443");
ChannelBuffer buf = ChannelBuffers.copiedBuffer(line, "UTF-8");
request.setContent(buf);
request.setHeader(HttpHeaders.Names.HOST, host);
request.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
request.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/xml");
request.setHeader(HttpHeaders.Names.CONTENT_LENGTH, Integer.toString(buf.capacity()));
ChannelFuture writeFuture = channel.write(request);
The client pipeline factory contains this:
pipeline.addLast("decoder", new HttpResponseDecoder());
pipeline.addLast("encoder", new HttpRequestEncoder());
// and then business logic.
...
The server pipeline factory contains this:
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("encoder", new HttpResponseEncoder());
// and then business logic.
....
So far so good. Client sends, server receives and decodes the request. The messageReceived method on my handler is called with the correct data.
In order to enable the SSL, I've taken some code from the SecureChat example and added to both client and server pipeline factories:
For the server:
SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();
engine.setUseClientMode(false);
pipeline.addLast("ssl", new SslHandler(engine));
// On top of the SSL handler, add the text line codec.
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(
8192, Delimiters.lineDelimiter()));
For the client:
SSLEngine engine = SecureChatSslContextFactory.getClientContext().createSSLEngine();
engine.setUseClientMode(true);
pipeline.addLast("ssl", new SslHandler(engine));
// On top of the SSL handler, add the text line codec.
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(
8192, Delimiters.lineDelimiter()));
Now when I send the request from the client, nothing seems to happen on the server. When I start up the applications, the server seems to connect (channelConnected is called), but when I send the message none of the data gets to the server (messageReceived is never called).
Is there something obviously wrong with what I am doing? Is this the way that https should work? Or is there a different method for sending http requests over ssl?
Thanks,
Weezn
You need to call SslHandler.handshake() on the client side. Check the example again its in there.
Oops, it seems like I copied and pasted too much from the SecureChat example.
Removing the DelimiterBasedFrameDecoder seems to fix the issue.

Login error connecting to salesforce.com from Flex

Has anyone suddenly encountered login errors from their users trying to connect to salesforce.com from a Flex app using as3salesforce.swc?
I get the following error... password removed to protect the innocent...
App Domain = null
Api Server name = na3.salesforce.com
_internalServerUrl = https://na3.salesforce.com/services/Soap/u/14.0
loading the policy file: https://na3.salesforce.com/services/Soap/cross-domain.xml
Your application must be running on a https server in order to use https to communicate with salesforce.com!
login with creds
loading the policy file: https://na3.salesforce.com/services/crossdomain.xml
Your application must be running on a https server in order to use https to communicate with salesforce.com!
invoke login
intServerUrl is null
intServerUrl = https://na3.salesforce.com/services/Soap/u/14.0
_invoke login
'5A5D3012-7717-E3C2-9B39-FFBBFF1F1B47' producer set destination to 'DefaultHTTPS'.
Method name is: login
'direct_http_channel' channel endpoint set to http://localhost/pm_server/pm/
'5A5D3012-7717-E3C2-9B39-FFBBFF1F1B47' producer sending message 'E32C7199-72C1-B258-B483-FFBC1641173D'
'direct_http_channel' channel sending message:
(mx.messaging.messages::HTTPRequestMessage)#0
body = "<se:Envelope xmlns:se="http://schemas.xmlsoap.org/soap/envelope/"><se:Header xmlns:sfns="urn:partner.soap.sforce.com"/><se:Body><login xmlns="urn:partner.soap.sforce.com" xmlns:ns1="sobject.partner.soap.sforce.com"><username>simon.palmer#dialectyx.com</username><password>******</password></login></se:Body></se:Envelope>"
clientId = (null)
contentType = "text/xml; charset=UTF-8"
destination = "DefaultHTTPS"
headers = (Object)#1
httpHeaders = (Object)#2
Accept = "text/xml"
SOAPAction = """"
X-Salesforce-No-500-SC = "true"
messageId = "E32C7199-72C1-B258-B483-FFBC1641173D"
method = "POST"
recordHeaders = false
timestamp = 0
timeToLive = 0
url = "https://na3.salesforce.com/services/Soap/u/14.0"
'5A5D3012-7717-E3C2-9B39-FFBBFF1F1B47' producer connected.
Method name is: login
Error: Ignoring policy file at https://na3.salesforce.com/crossdomain.xml due to meta-policy 'by-content-type'.
'5A5D3012-7717-E3C2-9B39-FFBBFF1F1B47' producer acknowledge of 'E32C7199-72C1-B258-B483-FFBC1641173D'.
responseType: Fault
Saleforce Soap Fault: sf:INVALID_LOGIN
INVALID_LOGIN: Invalid username, password, security token; or user locked out.
Comunication Error : sf:INVALID_LOGIN : INVALID_LOGIN: Invalid username, password, security token; or user locked out. : [object Object]
Obviously nobody else out there is building Flex apps on top of salesforce.com..
yippee, I'm first.
Anyhow, I just found out that this is a bug at salesforce.com as at 6th December 2008. The issue is that the scripts which handle login do not cope adequately with the redirect necessary because of load balancing on the salesforce.com servers.
It should be possible to go through the www front door of salesforce.com's api with a URL such as...
"https://www.salesforce.com/services/Soap/u/13.0";
where the 13 represents the version of their API you are targetting. However, all users are actually assigned to a specific server, so the front door should redirect the login request to the approriate place, and it doesn't if you are coming from Flex.
A workround is to specify your server in the URL, such as...
"https://na5.salesforce.com/services/Soap/u/13.0";
...which is what I was doing. That's fine if you are a single user accessing the same resources continually and your account remains attached to that server. However if...
You are distributing your app so anyone who has a salesforce.com enterprise account can log in OR
Your account gets moved because of some internal load balancing (which is what happened to me)
then the approach of providing a fixed server won't work.
The bug (as far as I understand it) is that the www route doesn't adequately redirect to your host server. Last intelligence was that it will be fixed "soon".
I wish I could mark this as the answer...

Resources