NoClassDefFoundError encountered while fixing CRLF sequence in HttpHeader - cookies

After performing Vera code scan on my code, a flaw was reported saying " Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting - CWE ID 113') on the below code.
public void writeCookies() {
for (final Cookie cookie : cookies) {
super.addCookie(cookie);
}
The flaw code reported is super.addCookie(cookie). To fix this I added below code
public void writeCookies() {
for (final Cookie cookie : cookies) {
cookie.setSecure(true);
ESAPI.httpUtilities().addCookie(((HttpServletResponse)super.getResponse()),cookie);
}
}
Now the Veracode scan doesn't report any flaw in the code. However, while running the application, I get NoClassDefFoundError as below
Error Message: javax.servlet.ServletException:
java.lang.NoClassDefFoundError:
org.apache.commons.fileupload.FileItemFactory Error Code: 500 Target
Servlet: com.ibm.ws.webcontainer.extension.DefaultExtensionProcessor
Error Stack: java.lang.NoClassDefFoundError:
org.apache.commons.fileupload.FileItemFactory
at java.lang.J9VMInternals.verifyImpl(Native Method)
at java.lang.J9VMInternals.verify(J9VMInternals.java:94)
at java.lang.J9VMInternals.initialize(J9VMInternals.java:171)
at java.lang.Class.forNameImpl(Native Method)
at java.lang.Class.forName(Class.java:180)
at org.owasp.esapi.util.ObjFactory.make(ObjFactory.java:74)
at org.owasp.esapi.ESAPI.httpUtilities(ESAPI.java:121)
My ESAPI.properties file is at location src/main/resources/ESAPI.properties
The content of ESAPI.properties file is
*
Encoder.AllowMultipleEncoding=false Encoder.AllowMixedEncoding=false
Encoder.DefaultCodecList=HTMLEntityCodec,PercentCodec,JavaScriptCodec
ESAPI.HTTPUtilities=org.owasp.esapi.reference.DefaultHTTPUtilities
*
Please suggest me on how to fix this NoClassDefFoundError...

Related

Logstash grok pattern to catch the first line with the string Exception

This is the an example log:
2022-01-07 11:05:01,185 [http-nio-8080-exec-526] WARN de.web.Main| = - Error while execute Request
javax.servlet.ServletException: com.cg.blart.web.HttpInvocationException: Invalid tenant session
at com.cg.blume.web.DispatchingServlet.doGet(DispatchingServlet.java:169)
at de.jinx.lee.web.AutoDBUpgradeDispatchingServlet.lambda$doGet$0(AutoDBUpgradeDispatchingServlet.java:200)
at de.jinx.lee.web.AutoDBUpgradeDispatchingServlet.addMDCKey(AutoDBUpgradeDispatchingServlet.java:297)
Caused by: com.cg.blume.web.HttpInvocationException: Invalid tenant session
at com.cg.blume.web.procedure.HttpSessionManager.get(HttpSessionManager.java:190)
at de.jinx.lee.web.session.leeHttpSessionManager.get(leeHttpSessionManager.java:76)
... 41 more
This ist the pattern so far:
^.*?Exception: +%{DATA:exception}$
The output i get is close but no cigar: "com.cg.blart.web.HttpInvocationException: Invalid tenant session". For the live of me i dont get it to match the whole line. Can you show me the way? The desired output is:
javax.servlet.ServletException: com.cg.blart.web.HttpInvocationException: Invalid tenant session
Here is a link for a test tool: https://grokdebug.herokuapp.com/
Solution was this pattern:
(?<DATA:mps_exception>.*?(Exception:).*)
It is explained here: https://www.elastic.co/guide/en/logstash/current/plugins-filters-grok.html#_custom_patterns

S3 : Java SDK : Delete Object tags throws "You must provide the Content-Length HTTP header" error

I am having trouble deleting tags on existing key.
SDK Version : compile('software.amazon.awssdk:s3:2.17.2')
Java version : 1.8
Error : software.amazon.awssdk.services.s3.model.S3Exception: You must provide the Content-Length HTTP header.
Code snippet:
DeleteObjectTaggingRequest deleteObjectTaggingRequest = DeleteObjectTaggingRequest.builder()
.bucket(bucketName)
.key(key)
.build();
s3Client.deleteObjectTagging(deleteObjectTaggingRequest);
Stack trace:
2021-07-22 17:12:46.365 ERROR 13564 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is software.amazon.awssdk.services.s3.model.S3Exception: You must provide the Content-Length HTTP header. (Service: S3, Status Code: 411, Request ID: 1626991966461970, Extended Request ID: 12789133)] with root cause
software.amazon.awssdk.services.s3.model.S3Exception: You must provide the Content-Length HTTP header. (Service: S3, Status Code: 411, Request ID: , Extended Request ID: )
at software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlPredicatedResponseHandler.handleErrorResponse(AwsXmlPredicatedResponseHandler.java:156) ~[aws-xml-protocol-2.17.2.jar:na]
at software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlPredicatedResponseHandler.handleResponse(AwsXmlPredicatedResponseHandler.java:106) ~[aws-xml-protocol-2.17.2.jar:na]
at software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlPredicatedResponseHandler.handle(AwsXmlPredicatedResponseHandler.java:84) ~[aws-xml-protocol-2.17.2.jar:na]
at software.amazon.awssdk.protocols.xml.internal.unmarshall.AwsXmlPredicatedResponseHandler.handle(AwsXmlPredicatedResponseHandler.java:42) ~[aws-xml-protocol-2.17.2.jar:na]
Any help on this would be greatly appreciated. Thank you

AWS Redis : JedisConnectionException: java.net.SocketException: Too many open files

I have configured redis using AWS Elasticache and connecting it through tomcat installed on AWS EC2.
Following is my code:
private JedisPool jedisPool = null;
#PostConstruct
private void initialiseJedisPools() {
try {
String redisHost = RESOURCES.getProperty("redis.master.host");
if(Objects.nonNull(redisHost)) {
Integer redisPort = Integer.valueOf(RESOURCES.getProperty("redis.master.port"));
jedisPool = new JedisPool(redisHost, redisPort);
}
} catch (NumberFormatException exception) {
logger.error("Exception occurred while initialising jedis pool.", exception);
}
}
public void addKey(String key, String value, Integer secondsToExpire) {
if (Objects.nonNull(jedisPool)) {
try (Jedis jedis = jedisPool.getResource()) {
jedis.set(key, value);
if (Objects.nonNull(secondsToExpire)) {
jedis.expire(key, secondsToExpire.intValue());
}
} catch (JedisException jedisException) {
logger.error("Exception thrown while adding key in cache.", jedisException);
}
}
}
Often a while I get the following error and I have to restart tomcat to make it work.
redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
at redis.clients.util.Pool.getResource(Pool.java:53)
at redis.clients.jedis.JedisPool.getResource(JedisPool.java:226)
.
.
.
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketException: Too many open files
at redis.clients.jedis.Connection.connect(Connection.java:207)
at redis.clients.jedis.BinaryClient.connect(BinaryClient.java:93)
at redis.clients.jedis.BinaryJedis.connect(BinaryJedis.java:1767)
at redis.clients.jedis.JedisFactory.makeObject(JedisFactory.java:106)
at org.apache.commons.pool2.impl.GenericObjectPool.create(GenericObjectPool.java:868)
at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:435)
at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:363)
at redis.clients.util.Pool.getResource(Pool.java:49)
... 10 more
Caused by: java.net.SocketException: Too many open files
at java.net.Socket.createImpl(Socket.java:460)
at java.net.Socket.getImpl(Socket.java:520)
at java.net.Socket.setReuseAddress(Socket.java:1449)
at redis.clients.jedis.Connection.connect(Connection.java:174)
... 17 more
I have tried increasing the ulimit for open files, configuring a JedisPoolConfig for maxTotal, maxIdle, minIdle, etc, but no success.
Please suggest.
We have also faced similar issue in past for jedis connection with error "java.net.SocketException: Too many open files"
This happens due to jedis connection not getting closed.
call jedisPool.returnResourse(jedis) or jedis.close()

javax.xml.ws.WebServiceException timeout from soap request using jax-ws

I am getting the following exception when I run my build in jenkins.
Here is what I did
I created java files from running the following command
wsimport -keep -verbose http://foobar.com/ws/server?wsdl
I copied the files created to my project and used it to construct the client stubs
Here is how my client looks
public class SoapClient {
private ServiceSoap soapService;
//30 secs
private static final Integer REQUEST_TIMEOUT_MILLI = 90000;
//15 secs
private static final Integer CONNECT_TIMEOUT_MILLI = 90000;
public SoapClient(){
Service service = new Service();
service.setHandlerResolver(new JaxWsHandlerResolver());
soapService = service.getServiceSoap();
((BindingProvider)soapService).getRequestContext()
.put(BindingProviderProperties.REQUEST_TIMEOUT,REQUEST_TIMEOUT_MILLI);
((BindingProvider)soapService).getRequestContext()
.put(BindingProviderProperties.CONNECT_TIMEOUT,CONNECT_TIMEOUT_MILLI);
}
public SoapResponse processRequest(String refNum){
SoapResponse response = null;
try {
response = soapService.requestInfo(refNum);
}
catch (Exception ex){
LOG.error("error connecting to Soap service, {}",ex.getLocalizedMessage());
LOG.error(ex.getMessage());
LOG.error(ex.getCause().toString());
ex.printStackTrace();
}
return response;
}
}
I have set connection and request timeouts above. I have increased upto 10 minutes. till I see the same exception. I have included the jaxws-rt dependency in my pom.xml
Here it is
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<jaxws.version>2.2.10</jaxws.version>
</dependency>
Here is the exception I am seeing
2016-05-05 04:43:40,337 [main] ERROR foo.bar.foobar.client.SoapClient - java.net.SocketTimeoutException: Read timed out
javax.xml.ws.WebServiceException: java.net.SocketTimeoutException: Read timed out
at com.sun.xml.ws.transport.http.client.HttpClientTransport.readResponseCodeAndMessage(HttpClientTransport.java:210)
at com.sun.xml.ws.transport.http.client.HttpTransportPipe.createResponsePacket(HttpTransportPipe.java:241)
at com.sun.xml.ws.transport.http.client.HttpTransportPipe.process(HttpTransportPipe.java:232)
at com.sun.xml.ws.transport.http.client.HttpTransportPipe.processRequest(HttpTransportPipe.java:145)
at com.sun.xml.ws.transport.DeferredTransportPipe.processRequest(DeferredTransportPipe.java:110)
at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
at com.sun.xml.ws.client.Stub.process(Stub.java:463)
at com.sun.xml.ws.client.sei.SEIStub.doProcess(SEIStub.java:191)
at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:108)
at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:92)
at com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:161)
at com.sun.proxy.$Proxy50.requestInfo(Unknown Source)
at
The exception seems to be sun related. I have read other posts. but none helped me actually. I am stuck here for two days and any help here would be much appreciated.
Thanks
EDIT
I pretty much see same issue as here. but no solution has been posted

Caused by: java.net.ConnectException: Connection refused: connect org.springframework.web.client.ResourceAccessException: I/O error on POST

I've the following CURL command which works very fine. But when using through java code. I am using WSO2 API Manager version 1.9.1
curl -k -d "grant_type=password&username=test&password=test" -H
"Authorization: Basic QU01dE04MXFrdzg5ZFNFTjk2Vm0waGgwWnBNYTpzeHcxbko3c2gzdm5NVVlmUDEzVmV1bWtsbTRh,
Content-Type: application/x-www-form-urlencoded" https://XXXXXX:8243/token
I developed the following code using RestTemplate API
public class Demo {
public static void main(String[] args) {
String url = "https://xxxxxxxx:8243/token";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Basic QU01dE04MXFrdzg5ZFNFTjk2Vm0waGgwWnBNYTpzeHcxbko3c2gzdm5NVVlmUDEzVmV1bWtsbTRh");
headers.add("Content-Type", "application/x-www-form-urlencoded");
headers.add("data", "grant_type=password&username=mahesh&password=mahesh00");
String json =" {\"data\":\"grant_type=password&username=test&password=test\"}";
HttpEntity<String> postEntity = new HttpEntity<String>(json, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response =restTemplate.exchange(url, HttpMethod.POST,postEntity,String.class);
System.out.println("\nSTATUS : "+ response.getStatusCode()+" "+response.getStatusCode().getReasonPhrase());
System.out.println("Response :"+ response.getBody());
}
}
When I execute below, I see the following error:
Exception in thread "main" org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://192.168.0.102:8243/token":java.security.cert.CertificateException: No subject alternative names present; nested exception is javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:580)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:530)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:448)
at com.java.pushNotifications.Demo.main(Demo.java:25)
Caused by: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1904)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:279)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:273)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1446)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:209)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:901)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:837)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1023)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1332)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1359)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1343)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153)
at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:81)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:569)
... 3 more
Caused by: java.security.cert.CertificateException: No subject alternative names present
at sun.security.util.HostnameChecker.matchIP(HostnameChecker.java:142)
at sun.security.util.HostnameChecker.match(HostnameChecker.java:91)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:347)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:203)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1428)
... 17 more
You forgot to specify the port in your java code:
https://192.168.0.102:/token
It should be:
https://192.168.0.102:8243/token
You also forgot to hide the IP here as you did with the curl command, but since it is an internal IP there is no reason to bother with it, it means nothing outside of your own LAN. So I am not masking it either.
I were facing the similar issue-
org.springframework.web.client.ResourceAccessException: I/O error on
POST request for
"http://hostname:port_number/projectname/inbound/message": Connection
refused: connect; nested exception is java.net.ConnectException:
Connection refused: connect
So, I am using application.yml under src/main/resources and I changed the host value from server ip_address to localhost for testing with Swagger on my PC,
gui:
protocol: http
host: localhost
port: 8280
Hope any bit of the information with help someone.