SSLSocketImpl.startHandshake() throws SSLHanshakeException/EOFException when resuming cached sessions - java

Using Apache FTPSClient to listFiles(String)....
The aplication crashes sometimes after resuming an SSL Session and then calling sslSocketImpl.startHandshake() from the Apache FTPSClient code.
I set javax.net.debug to print the ssl information...
System.setProperty("javax.net.debug", "all");
And this is what I get.
%% Client cached [Session-3, SSL_RSA_WITH_3DES_EDE_CBC_SHA]
%% Try resuming [Session-3, SSL_RSA_WITH_3DES_EDE_CBC_SHA] from port 4149
*** ClientHello, TLSv1
....
main, received EOFException: error
main, handling exception: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
main, SEND TLSv1 ALERT: fatal, description = handshake_failure
main, WRITE: TLSv1 Alert, length = 2
[Raw write]: length = 7
0000: 15 03 01 00 02 02 28 ......(
main, called closeSocket()
[Mon Aug 30 17:41:52 PDT 2010][class com.smgtec.sff.fileupload.poller.BasicFTPAccess] - Could not list directory: sqjavax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:808)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1096)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1123)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1107)
at com.smgtec.sff.fileupload.poller.FixedFTPSClient._openDataConnection_(FixedFTPSClient.java:525)
at org.apache.commons.net.ftp.FTPClient.initiateListParsing(FTPClient.java:2296)
at org.apache.commons.net.ftp.FTPClient.initiateListParsing(FTPClient.java:2269)
Padded plaintext before ENCRYPTION: len = 32
0000: 50 41 at org.apache.commons.net.ftp.FTPClient.listFiles(FTPClient.java:2046)
at com.smgtec.sff.fileupload.poller.BasicFTPAccess.listFiles(BasicFTPAccess.java:100)
at com.smgtec.sff.fileupload.poller.FTPPoller.addFileForProcessing(FTPPoller.java:67)
at com.smgtec.sff.fileupload.poller.FTPPoller.main(FTPPoller.java:385)
Caused by: java.io.EOFException: SSL peer shut down incorrectly
at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:333)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:789)
... 10 more
We also have jscape FTPS client here and it produces the same problem.

I suggest you include some retry logic in your FTPPoller - it looks like the host is closing the connection rather than your code. We used to see occasional connection closed by remote host errors which are best handled by simply retrying.

I solved it like this using SSLSession.invalidate() it seems to work now... although we aren't using FTPS anymore. If this is a true solution there is a problem in Apache commons-net FTPSClient or the FTP Server we are connecting to.
ftp = new FTPSClient()
{
private Socket socket;
protected Socket _openDataConnection_(int command, String arg) throws IOException
{
if (socket != null && socket instanceof SSLSocket)
{
// We have problems resuming cached SSL Sessions. Exceptions are
// thrown and the system crashes... So we invalidate each SSL
// session we used last.
SSLSocket sslSocket = (SSLSocket) socket;
sslSocket.getSession().invalidate();
}
socket = super._openDataConnection_(command, arg);
return socket;
}
};
BTW I believe we were connecting to a FileZilla FTP server. I suspect this fix will cause more network chatter passing back and forth keys/certs and so forth.

Related

java SSLEngine says NEED_WRAP, call .wrap() and still NEED_WRAP

I am seeing a weird issue with SSLEngine and wondering if there is an issue with my code or SSLEngine. Here is the order in which I see things
HandshakeStatus is NEED_WRAP
We call SSLEngine.WRAP
after, there is ZERO data written to the buffer, and SSLEngineResult.result=OK(not overflow nor underflow :( ) and HandshakeStatus is STILL NEED_WRAP
Most important question: How to debug thoroughly? How to 'see' each message somehow? I can capture the byte stream easily enough but is there some library that can parse that into SSL handshake objects?
line 298 (recording previous handshake status) to line 328(where we throw the exception with info) is the relevant code here
https://github.com/deanhiller/webpieces/blob/sslEngineFartingExample/core/core-ssl/src/main/java/org/webpieces/ssl/impl/AsyncSSLEngine3Impl.java
The stack trace was
2019-06-21 08:58:24,562 [-] [webpiecesThreadPool6] Caller+1 at org.webpieces.util.threading.SessionExecutorImpl$RunnableWithKey.run(SessionExecutorImpl.java:123)
ERROR: Uncaught Exception
java.lang.IllegalStateException: Engine issue. hsStatus=NEED_WRAP status=OK previous hsStatus=NEED_WRAP
at org.webpieces.ssl.impl.AsyncSSLEngine3Impl.sendHandshakeMessageImpl(AsyncSSLEngine3Impl.java:328)
at org.webpieces.ssl.impl.AsyncSSLEngine3Impl.sendHandshakeMessage(AsyncSSLEngine3Impl.java:286)
at org.webpieces.ssl.impl.AsyncSSLEngine3Impl.doHandshakeWork(AsyncSSLEngine3Impl.java:133)
at org.webpieces.ssl.impl.AsyncSSLEngine3Impl.doHandshakeLoop(AsyncSSLEngine3Impl.java:246)
at org.webpieces.ssl.impl.AsyncSSLEngine3Impl.unwrapPacket(AsyncSSLEngine3Impl.java:210)
at org.webpieces.ssl.impl.AsyncSSLEngine3Impl.doWork(AsyncSSLEngine3Impl.java:109)
at org.webpieces.ssl.impl.AsyncSSLEngine3Impl.feedEncryptedPacket(AsyncSSLEngine3Impl.java:82)
at org.webpieces.nio.impl.ssl.SslTCPChannel$SocketDataListener.incomingData(SslTCPChannel.java:175)
at org.webpieces.nio.impl.threading.ThreadDataListener$1.run(ThreadDataListener.java:26)
at org.webpieces.util.threading.SessionExecutorImpl$RunnableWithKey.run(SessionExecutorImpl.java:121)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
any ideas? How can I really dig into this further? My preference is a library that takes bytes and spits out ssl objects representing each handshake message or decrypted packet(with any header info that comes with the original encrypted thing).
Specifically, here is the code mentioned above
HandshakeStatus previousStatus = sslEngine.getHandshakeStatus();
//CLOSE and all the threads that call feedPlainPacket can have contention on wrapping to encrypt and
//must synchronize on sslEngine.wrap
Status lastStatus;
HandshakeStatus hsStatus;
synchronized (wrapLock ) {
HandshakeStatus beforeWrapHandshakeStatus = sslEngine.getHandshakeStatus();
if (beforeWrapHandshakeStatus != HandshakeStatus.NEED_WRAP)
throw new IllegalStateException("we should only be calling this method when hsStatus=NEED_WRAP. hsStatus=" + beforeWrapHandshakeStatus);
//KEEEEEP This very small. wrap and then listener.packetEncrypted
SSLEngineResult result = sslEngine.wrap(SslMementoImpl.EMPTY, engineToSocketData);
lastStatus = result.getStatus();
hsStatus = result.getHandshakeStatus();
}
log.trace(()->mem+"write packet pos="+engineToSocketData.position()+" lim="+
engineToSocketData.limit()+" status="+lastStatus+" hs="+hsStatus);
if(lastStatus == Status.BUFFER_OVERFLOW || lastStatus == Status.BUFFER_UNDERFLOW)
throw new RuntimeException("status not right, status="+lastStatus+" even though we sized the buffer to consume all?");
boolean readNoData = engineToSocketData.position() == 0;
engineToSocketData.flip();
try {
CompletableFuture<Void> sentMsgFuture;
if(readNoData) {
log.trace(() -> "ssl engine is farting. READ 0 data. hsStatus="+hsStatus+" status="+lastStatus);
throw new IllegalStateException("Engine issue. hsStatus="+hsStatus+" status="+lastStatus+" previous hsStatus="+previousStatus);
//A big hack since the Engine was not working in live testing with FireFox and it would tell us to wrap
//and NOT output any data AND not BufferOverflow.....you have to do 1 or the other, right!
//instead cut out of looping since there seems to be no data
//sslEngineIsFarting = true;
//sentMsgFuture = CompletableFuture.completedFuture(null);
thanks,
Dean
System.setProperty("jdk.tls.server.protocols", "TLSv1.2");
System.setProperty("jdk.tls.client.protocols", "TLSv1.2");
The system property should be set before the JSSE get loaded. For example, set the property within command line. Is it the cause that the system property does not work for you?
... the SSLEngine tells us we need to WRAP which is correct as we need to be replying with a close_notify as well to prevent truncation attacks BUT instead the engine returns 0 bytes and tells us the state of the engine is still NEED_WRAP.
TLS 1.3 is using a half-close policy (See RFC 8446). When receiving the close_notify, the inbound side will be closed and the outbound side keeps open. The local side cannot receive any data, but is allowed to send more application data.
There are a few compatibility impact by the half-close policy (See JDK 11 release note, https://www.oracle.com/technetwork/java/javase/11-relnote-issues-5012449.html). The system property, "jdk.tls.acknowledgeCloseNotify", can be used as a workaround. For more details, please refer to the JDK 11 release note.
oh, even better, downgrading to 1.8.0_111 yields success
2019-06-30 00:11:54,813 [main] Caller+1 at
WEBPIECESxPACKAGE.DevelopmentServer.main(DevelopmentServer.java:32)
INFO: Starting Development Server under java version=1.8.0_111
webpiecesThreadPool5, READ: TLSv1.2 Alert, length = 26
webpiecesThreadPool2, RECV TLSv1.2 ALERT: warning, close_notify
webpiecesThreadPool2, closeInboundInternal()
webpiecesThreadPool2, closeOutboundInternal()
webpiecesThreadPool5, RECV TLSv1.2 ALERT: warning, close_notify
webpiecesThreadPool5, closeInboundInternal()
webpiecesThreadPool5, closeOutboundInternal()
webpiecesThreadPool2, SEND TLSv1.2 ALERT: warning, description = close_notify
webpiecesThreadPool5, SEND TLSv1.2 ALERT: warning, description = close_notify
webpiecesThreadPool2, WRITE: TLSv1.2 Alert, length = 26
webpiecesThreadPool5, WRITE: TLSv1.2 Alert, length = 26
Ok, more and more this seems like a jdk bug and this seems to prove it now. My log shows I was on jdk11.0.3(on a MAC)
2019-06-29 23:37:18,793 [main][] [-] Caller+1 at
WEBPIECESxPACKAGE.DevelopmentServer.main(DevelopmentServer.java:32)
INFO: Starting Development Server under java version=11.0.3
I used debug ssl flag settings of
-Djavax.net.debug=ssl:handshake:verbose:keymanager:trustmanager -Djava.security.debug=access:stack
I surrounded all my calls to sslEngine.wrap and sslEngine.unwrap with my own logs as well and thankfully everyone had the thread name in their logs as well.
It seems when clients send a warning of this
javax.net.ssl|DEBUG|14|webpiecesThreadPool1|2019-06-29 23:27:14.860
MDT|Alert.java:232|Received alert message (
"Alert": {
"level" : "warning",
"description": "close_notify"
}
)
the SSLEngine tells us we need to WRAP which is correct as we need to be replying with a close_notify as well to prevent truncation attacks BUT instead the engine returns 0 bytes and tells us the state of the engine is still NEED_WRAP.
ALSO, there was ZERO ssl debug logs from java between my logs before and after the sslEngine.wrap call almost like the sslEngine farted and did nothing.
Then, I thought I would be really cool and added this as the first lines in main() method
System.setProperty("jdk.tls.server.protocols", "TLSv1.2");
System.setProperty("jdk.tls.client.protocols", "TLSv1.2");
but the selected version in the debug info was still TLSv1.3....grrrrrr...oh well, I give up.

"Remote host closed connection during handshake" when connecting to FTP server using Commons Net FTPSClient

My code (I use -Dhttps.protocols=TLSv1.2 VM argument when run):
FTPSClient ftpClient = new FTPSClient("TLS", false);
ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
ftpClient.setAuthValue("TLS");
ftpClient.connect("myhost", 990);
ftpClient.login("mylogin", "mypassword");
Stack trace:
javax.net.ssl.SSLHandshakeException: Remote host closed connection
during handshake
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:992)
// too many traces...
Caused by: java.io.EOFException: SSL peer shut down incorrectly
at sun.security.ssl.InputRecord.read(InputRecord.java:505)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
... 33 more
Log from WinSCP (I can send files using WinSCP):
536 Copying 1 files/directories to remote directory "/" 536 PrTime:
Yes; PrRO: No; Rght: rw-r--r--; PrR: No (No); FnCs: N; RIC: 0100;
Resume: S (102400); CalcS: Yes; Mask: . 536 TM: B; ClAr: No;
RemEOF: No; RemBOM: No; CPS: 0; NewerOnly: No; InclM: ; ResumeL: 0 536
AscM: *.*html; *.htm; *.txt; *.php; *.php3; *.cgi; *.c; *.cpp; *.h;
*.pas; *.bas; *.tex; *.pl; *.js; .htaccess; *.xtml; *.css; *.cfg; *.ini; *.sh; *.xml 539 File: 'C:\Users\trescon.jramos\Documents\cliente-dados.sql'
[2016-10-06T16:34:29.298Z] [4869] 557 Copying
"C:\Users\trescon.jramos\Documents\cliente-dados.sql" to remote
directory started. 560 Binary transfer mode selected. 560 Iniciando
carregamento de C:\Users\trescon.jramos\Documents\cliente-dados.sql
560 TYPE I 562 200 Type set to I 563 PASV 568 227 Entering Passive
Mode (10,28,14,218,250,0) 569 STOR cliente-dados.sql 569 Conectando a
10.28.14.218:64000... 575 150 Opening data channel for file upload to server of "/cliente-dados.sql" 579 Session ID reused 579 Using
TLSv1.2, cipher TLSv1/SSLv3: ECDHE-RSA-AES256-GCM-SHA384, 2048 bit
RSA, ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA
Enc=AESGCM(256) Mac=AEAD 580 Conexão SSL estabelecida 586 226
Successfully transferred "/cliente-dados.sql" 586 MFMT 20161006163429
cliente-dados.sql 590 213 modify=20161006163429; /cliente-dados.sql
590 Carregamento bem-sucedido 591 Transfer done:
'C:\Users\trescon.jramos\Documents\cliente-dados.sql' [4869]
You are connecting to port 990, what is an implicit FTPS port. Yet, you are passing false to isImplicit argument of FTPSClient constructor.
Either pass true, if you really want to use the implicit FTPS:
FTPSClient ftpClient = new FTPSClient("TLS", true);
Or actually, you should really use an explicit FTPS and the default FTP port 21 (as the implicit FTPS is non-standard legacy compatibility hack):
FTPSClient ftpClient = new FTPSClient();
// ...
ftpClient.connect("myhost");
In other words, all you need to use FTPS is use FTPSClient, no additional arguments or calls are needed.

Connection refused after SSL handshake

I'm trying to connect to a WCF server that needs a client cert. I've imported the client cert into a JKS file locally and provided the cert location to the JAXWS client using the -Djavax.net.ssl*** options. The SSL debug prints the below information before it finally gets a Connection refused exception. Apparently the handshake seems to successful but then a closeInternal(true) is called and then the exception. Any clues/ideas are much appreciated. Thanks in advance.
... no IV used for this cipher
main, WRITE: TLSv1 Change Cipher Spec, length = 17
*** Finished
verify_data: { 68, 26, 22, 198, 55, 196, 10, 167, 6, 30, 206, 143 }
***
main, WRITE: TLSv1 Handshake, length = 32
main, READ: TLSv1 Change Cipher Spec, length = 17
main, READ: TLSv1 Handshake, length = 32
*** Finished
verify_data: { 233, 31, 138, 146, 138, 210, 137, 249, 81, 126, 169, 166 }
***
%% Cached client session: [Session-3, SSL_RSA_WITH_RC4_128_MD5]
main, READ: TLSv1 Application Data, length = 469
main, called close()
main, called closeInternal(true)
main, SEND TLSv1 ALERT: warning, description = close_notify
main, WRITE: TLSv1 Alert, length = 18
Exception in thread "main" com.sun.xml.internal.ws.wsdl.parser.InaccessibleWSDLException: 2 counts of InaccessibleWSDLException.
java.net.ConnectException: Connection refused: connect
java.net.ConnectException: Connection refused: connect
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.tryWithMex(RuntimeWSDLParser.java:161)
at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse(RuntimeWSDLParser.java:133)
at com.sun.xml.internal.ws.client.WSServiceDelegate.parseWSDL(WSServiceDelegate.java:254)
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:217)
at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:165)
at com.sun.xml.internal.ws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:93)
at javax.xml.ws.Service.<init>(Service.java:56)
at com.acs.echo.gen.EchoService.<init>(EchoService.java:46)
at com.acs.echo.client.EchoClient.invokeWebService(EchoClient.java:43)
at com.acs.echo.client.EchoClient.main(EchoClient.java:17)
The SSL handshake and TCP connection to the server are succeeding, but the retrieval of the WSDL is failing. It appears to be coming from a non-SSL host that is giving you 'connection refused', which means that nothing is listened at the port specified in the WSDL RL, or maybe an intervening firewall has vetoed the connect attempt.

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure Error in APN

I am trying to send push notification to iPhone using Java-pns but I am getting the following error...
javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
This is my code...
String token="95076d2846e8979b46efd1884206a590d99d0f3f6139d947635ac4186cdc5942";
String host = "gateway.sandbox.push.apple.com";
int port = 2195;
String payload = "{\"aps\":{\"alert\":\"Message from Java o_O\"}}";
NotificationTest.verifyKeystore("res/myFile.p12", "password", false);
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(getClass().getResourceAsStream("res/myFile.p12"), "password".toCharArray());
KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance("SunX509");
keyMgrFactory.init(keyStore, "password".toCharArray());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyMgrFactory.getKeyManagers(), null, null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(host, port);
String[] cipherSuites = sslSocket.getSupportedCipherSuites();
sslSocket.setEnabledCipherSuites(cipherSuites);
sslSocket.startHandshake();
char[] t = token.toCharArray();
byte[] b = Hex.decodeHex(t);
OutputStream outputstream = sslSocket.getOutputStream();
outputstream.write(0);
outputstream.write(0);
outputstream.write(32);
outputstream.write(b);
outputstream.write(0);
outputstream.write(payload.length());
outputstream.write(payload.getBytes());
outputstream.flush();
outputstream.close();
System.out.println("Message sent .... ");
For NotificationTest.verifyKeystore I am getting that this valid is File and Keystore.
I am not understanding why I am getting this error.
This is my error log...
** CertificateRequest
Cert Types: RSA, DSS, ECDSA
Cert Authorities:
<empty>
[read] MD5 and SHA1 hashes: len = 10
0000: 0D 00 00 06 03 01 02 40 00 00 .......#..
** ServerHelloDone
[read] MD5 and SHA1 hashes: len = 4
0000: 0E 00 00 00 ....
** Certificate chain
**
** ClientKeyExchange, RSA PreMasterSecret, TLSv1
[write] MD5 and SHA1 hashes: len = 269
...
main, READ: TLSv1 Alert, length = 2
main, RECV TLSv1 ALERT: fatal, handshake_failure
main, called closeSocket()
main, handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
I am not understanding why Cert Authorities is empty?
I recommend that you use keytool -list to compare the keystore on the client with those known to the server. The handshake error you are getting is because the Server has done it's hello and is expecting a Client Certificate in reply. You are not sending one. To fix this the PKCS12 certificate should be converted to PEM format (using openssl is one way) and then imported into a keystore using the keytool.
I suspect if you fix this by importing a client certificate into the keystore, then you will hit a second error. The second error will be about the empty CA certs - probably because you don't have a CA cert that is known to your server in your keystore. Import your CA and try again.
Looks like you need to install "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files". This solved the issue for me.
To Send Push Notification to iPhone/ iPad I have used JavaPNS.
It is very easy to use and It worked for me.
We can simply follow This to use it.

"bad record MAC" SSL error between Java and PortgreSQL

We've got here a problem of random disconnections between our Java apps and our PostgreSQL 8.3 server with a "bad record MAC" SSL error.
We run Debian / Lenny on both side. On the client side, we see :
main, WRITE: TLSv1 Application Data, length = 104
main, READ: TLSv1 Application Data, length = 24
main, READ: TLSv1 Application Data, length = 104
main, WRITE: TLSv1 Application Data, length = 384
main, READ: TLSv1 Application Data, length = 24
main, READ: TLSv1 Application Data, length = 8216
%% Invalidated: [Session-1, SSL_RSA_WITH_3DES_EDE_CBC_SHA]
main, SEND TLSv1 ALERT: fatal, description = bad_record_mac
main, WRITE: TLSv1 Alert, length = 24
main, called closeSocket()
main, handling exception: javax.net.ssl.SSLException: bad record MAC
2010-03-09 02:36:27,980 WARN org.hibernate.util.JDBCExceptionReporter.logExceptions(JDBCExceptionReporter.java:100) - SQL Error: 0, SQLState: 08006
2010-03-09 02:36:27,980 ERROR org.hibernate.util.JDBCExceptionReporter.logExceptions(JDBCExceptionReporter.java:101) - An I/O error occured while sending to the backend.
2010-03-09 02:36:27,981 ERROR org.hibernate.transaction.JDBCTransaction.toggleAutoCommit(JDBCTransaction.java:232) - Could not toggle autocommit
org.postgresql.util.PSQLException: An I/O error occured while sending to the backend.
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:220)
at org.postgresql.jdbc2.AbstractJdbc2Connection.executeTransactionCommand(AbstractJdbc2Connection.java:650)
at org.postgresql.jdbc2.AbstractJdbc2Connection.commit(AbstractJdbc2Connection.java:670)
at org.postgresql.jdbc2.AbstractJdbc2Connection.setAutoCommit(AbstractJdbc2Connection.java:633)
at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.jdbc.datasource.SingleConnectionDataSource$CloseSuppressingInvocationHandler.invoke(SingleConnectionDataSource.java:336)
at $Proxy17.setAutoCommit(Unknown Source)
at org.hibernate.transaction.JDBCTransaction.toggleAutoCommit(JDBCTransaction.java:228)
at org.hibernate.transaction.JDBCTransaction.rollbackAndResetAutoCommit(JDBCTransaction.java:220)
at org.hibernate.transaction.JDBCTransaction.rollback(JDBCTransaction.java:196)
at org.hibernate.ejb.TransactionImpl.rollback(TransactionImpl.java:85)
at org.springframework.orm.jpa.JpaTransactionManager.doRollback(JpaTransactionManager.java:482)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:823)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:800)
at org.springframework.transaction.interceptor.TransactionAspectSupport.completeTransactionAfterThrowing(TransactionAspectSupport.java:339)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:635)
...
Caused by: javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLException: bad record MAC
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.checkEOF(SSLSocketImpl.java:1255)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.checkWrite(SSLSocketImpl.java:1267)
at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:43)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123)
at org.postgresql.core.PGStream.flush(PGStream.java:508)
at org.postgresql.core.v3.QueryExecutorImpl.sendSync(QueryExecutorImpl.java:692)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:193)
... 22 more
Caused by: javax.net.ssl.SSLException: bad record MAC
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:190)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1611)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1569)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:850)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:746)
at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:75)
at org.postgresql.core.VisibleBufferedInputStream.readMore(VisibleBufferedInputStream.java:135)
at org.postgresql.core.VisibleBufferedInputStream.ensureBytes(VisibleBufferedInputStream.java:104)
at org.postgresql.core.VisibleBufferedInputStream.read(VisibleBufferedInputStream.java:186)
at org.postgresql.core.PGStream.Receive(PGStream.java:445)
at org.postgresql.core.PGStream.ReceiveTupleV3(PGStream.java:350)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1322)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:194)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:451)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:350)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:254)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1808)
at org.hibernate.loader.Loader.doQuery(Loader.java:697)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
at org.hibernate.loader.Loader.loadCollection(Loader.java:2015)
at org.hibernate.loader.collection.CollectionLoader.initialize(CollectionLoader.java:59)
at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:587)
at org.hibernate.event.def.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:83)
at org.hibernate.impl.SessionImpl.initializeCollection(SessionImpl.java:1743)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:366)
at org.hibernate.collection.PersistentSet.add(PersistentSet.java:212)
...
the cypher suites SSL_RSA_WITH_3DES_EDE_CBC_SHA or SSL_RSA_WITH_RC4_128_SHA were used.
We tried on the client side :
the OpenJDK package
the sun JDK package
the sun tar package
the libbcprov-java package
the PostgreSQL driver 8.3 instead of 8.4
On the server side we see :
2010-03-01 08:26:05 CET [18513]: [161833-1] LOG: SSL error: sslv3 alert bad record mac
2010-03-01 08:26:05 CET [18513]: [161834-1] LOG: could not receive data from client: Connection reset by peer
2010-03-01 08:26:05 CET [18513]: [161835-1] LOG: unexpected EOF on client connection
the error type seams to be SSL_R_SSLV3_ALERT_BAD_RECORD_MAC.
the SSL layer is configured with :
ssl_ciphers = 'ALL:!ADH:!LOW:!EXP:!MD5:#STRENGTH'
and on the server side we changed the cipher suites to :
'ALL:!SSLv2:!MEDIUM:!AES:!ADH:!LOW:!EXP:!MD5:#STRENGTH'
but none of these changes fixed the problem. Suggestions appreciated !
I don't know how Java deals with it, but a number of vendors recently released security updates that disabled SSL renegotiation support, sometimes in broken ways. Some have been fixed since, some not. This could be your problem, in case this is something that happens after a fairly large amount of data (512Mb by default) has passed over a connection. Since you're likely using a connection pool, that seems quite possible.
In PostgreSQL 8.4.3 (due out this week), we have added a configuration parameter that lets you disable SSL renegotiation completely - that might be worth a try. (there are also new versions in the previous trees (like 8.3) that contain this feature)

Categories

Resources