Skip to content

Allow to set max BIO memory size - #6123

Closed
normanmaurer wants to merge 2 commits into
4.1from
bio_mem_size
Closed

normanmaurer wants to merge 2 commits into
4.1from
bio_mem_size

Conversation

@normanmaurer

@normanmaurer normanmaurer commented Dec 9, 2016 •

Copy link
Copy Markdown
Member

Motivation:

By default openssl uses 17k bytes as memory size for its BIO. This can become very wasteful if you need to handle a lot of concurrent connections. We should allow to adjust the used memory and so trade memory usage with cpu usage.

Modification:

  • Allow to adjust the max memory used by the BIO
  • Adjust SSLEngine implementation to not assume 17k buffers.

Result:

Its now possible to use smaller buffers when using openssl based SSLEngine.

@normanmaurer

Copy link
Copy Markdown
Member Author

@trustin @nmittler @Scottmitch this allows to constumize the max number of bytes that are buffered by the BIO. By default it uses 17k buffers which means the whole SSL record can be buffered. The problem is that this may result in problems as you want to handle a lot of concurrent connections. When you lower the number of bytes in the buffer you can safe memory but need more CPU as you will need more often do JNI calls. So as always there are tradeoffs ;)

This is related to netty/netty-tcnative#205

Also @siyengar check this... The old code did not always handle the case correctly when the size was not the default one, with this change it does (or at least it seems ;)).


/**
* Returns if remote initiated renegotiation is supported or not.
*/

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAJOR A getX() method which returns a boolean should be named isX() rule

@sunng87

sunng87 commented Dec 9, 2016

Copy link
Copy Markdown
Contributor

@normanmaurer is it possible to specify max bio size for read/write buffer individually? In our application, the max request size is 5KB while there is no response size limit. It would be better in control if we can set different size for read/write buffer.

@normanmaurer

normanmaurer commented Dec 9, 2016 via email

Copy link
Copy Markdown
Member Author

@johnou

johnou commented Dec 9, 2016

Copy link
Copy Markdown
Contributor

@normanmaurer for next 4.0, right? 🎱

@normanmaurer

Copy link
Copy Markdown
Member Author

@johnou Not 100 % sure yet as I want to do some more testing just to be 100 % sure all works (which seems to be the case so far)

final OpenSslEngineMap engineMap = new DefaultOpenSslEngineMap();
volatile boolean rejectRemoteInitiatedRenegotiation;
private volatile boolean rejectRemoteInitiatedRenegotiation;
private volatile int maxBioSize = MAX_BIO_SIZE;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@normanmaurer I must be missing something ... where is this property used?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AccessController.doPrivileged(new PrivilegedAction<Integer>() {
@Override
public Integer run() {
return Math.min(0, SystemPropertyUtil.getInt("io.netty.handler.ssl.openssl.maxBioSize", 0));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is 0 a good default/min?

Also can we clarify the units here (bytes)?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes as it uses the default 17k here then. Let me add some Javadoc explaining it and also make it clear it's about bytes

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok gotcha ... 0 means take OpenSSL's default.

* needed each {@link ReferenceCountedOpenSslEngine} will consume 2 * maxBioSize of native memory. Using {@code 0}
* will use the default value of 16 kb. Using a lower number will trade memory usage with higher cpu-usage.
*/
public void setMaxBioSize(int maxBioSize) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we allow zero?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, see above

@@ -438,9 +437,11 @@ private int writeEncryptedData(final ByteBuffer src, int len) {
netWrote = SSL.writeToBIO(networkBIO, addr, len);
if (netWrote >= 0) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should this condition be consistent with the one you changed above?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, let me fix

return new SSLEngineResult(rs, hs, bytesConsumed, bytesProduced);
private void checkRetryBioOperation(String operation) throws SSLException {
if (!SSL.shouldRetryBIO(networkBIO)) {
// The BIO operation did return <= 0 but we should not retry. Something is seriously wrong

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

did return -> returned

pendingNetResult = readPendingBytesFromBIO(dst, bytesConsumed, bytesProduced, status);
return pendingNetResult != null ? pendingNetResult : CLOSED_NOT_HANDSHAKING;
// Check to see if the engine wrote data into the network BIO
pendingNet = SSL.pendingWrittenBytesInBIO(networkBIO);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this call necessary? this method was already called on line 633.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes but only if closeAll() was called, let me move it into the if block FTW

if (pendingNetResult != null) {
return pendingNetResult;
}
if (bytesConsumed == 0 && (pendingNet = SSL.pendingWrittenBytesInBIO(networkBIO)) > 0) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see the comments above but can you remind me why this is necessary? it seems like we always call readEncryptedData after writePlaintextData (unless there is an error and we return early anyways). so I guess it is possible there is already data in the BIO independent of this function (handshake maybe)?

Here is the original commit bad8e0d#diff-6ba8edb6d8a5a127eba9cf97911c6f14R544

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually we can remove this as we handle the case for handshake data above

if (isOutboundDone()) {
shutdown();
return CLOSED;
} else {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: remove else as you return above

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

if (!dst.hasRemaining()) {
// Move to the next dst buffer as this one is full.
dstsOffset++;
} else {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: make this an else if() and add an else for slightly less indentation.

}
}
}
if (pendingAppData() > 0) {

@Scottmitch Scottmitch Dec 9, 2016 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you explain why this was removed? is it no longer possible for the encryption portion to generate more data than can fit in the destination buffers when decrypted? the capacity vs packetLength we check above is against the encrypted length not the decrypted length, right? Is the extra iteration over dsts even necessary ... if we can just deal with the BUFFER_OVERFLOW at the end instead of trying to check upfront based off of encrypted length?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes it's not possible to have any leftover... also we need to check upfront as the SSLEngine should not keep data in internal buffers between unwrap / wrap calls

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

now that we explicitly disable compression ... the length check up front should be good enough. I wonder if we can improve the length check to not always just require max length (not sure if that would be beneficial or not).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let us consider this as a follow up.

@normanmaurer
normanmaurer force-pushed the bio_mem_size branch 2 times, most recently from 5c6f900 to 963f1fa Compare December 10, 2016 19:47
SSLContext.setOptions(ctx, SSL.SSL_OP_SINGLE_DH_USE);
SSLContext.setOptions(ctx, SSL.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
// We not support compression as the moment so not use it.
SSLContext.setOptions(ctx, SSL.SSL_OP_NO_COMPRESSION);

@johnou johnou Dec 13, 2016 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Compression was never supported? I suppose it is only safe with up to date clients anyway (CRIME vulnerability).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah it was never supported... We just not disabled it explicit before which we should do anyway.

SSLContext.setOptions(ctx, SSL.SSL_OP_SINGLE_ECDH_USE);
SSLContext.setOptions(ctx, SSL.SSL_OP_SINGLE_DH_USE);
SSLContext.setOptions(ctx, SSL.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
// We not support compression as the moment so not use it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We do not support compression at the moment

@johnou johnou left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

checked it with JRE9? Maybe already happening on CI?


// IMPORTANT:
//
// This calculation only works as we not support compression and set

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as we do not support

@siyengar

Copy link
Copy Markdown

I was reading the diff, and there are several changes in here including removing compression. @normanmaurer what exactly in the previous code assumed a default buffer size?

@normanmaurer

Copy link
Copy Markdown
Member Author

@siyengar we never supported compression, so if openssl was compiled with it and it was used our implementation did produce errors. We not always checked correctly for pending data and so my missed to unwrap/wrap everything. This commit fixes it when the buffer can not hold the full record.

@siyengar

siyengar commented Dec 14, 2016 •

Copy link
Copy Markdown

Thanks @normanmaurer, to clarify the previous implementation was only affected when compression was used?

new SSLEngineResult(isOutboundDone() ? CLOSED : OK,
NEED_UNWRAP, bytesConsumed, bytesProduced);

if (pendingNet <= 0) {

@siyengar siyengar Dec 14, 2016 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in this case src could potentially have more bytes to SSL_write right? This would be a bit pessimistic to return to the loop.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@siyengar not sure what you are suggesting here. Can you be more clear what you think should be done ?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

its not necessary, however maybe a check like this may help

if (pendingNet <= 0 && !src.hasRemaining()) {...

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OpenSSL is saying it needs some data to be read/unwrapped in this condition. I wouldn't expect this condition to change even if src (or other elements in the srcs array) have more data.

Can you clarify under what condition you would expect subsequent writes to succeed without reading/unwrapping data? Also we just tried to write src and failed ... can you explain why you expect different results if we tried to write src again (assuming there is data left to write)?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah nvm, I misunderstood. It's an SSL_write which is returning a WANT_READ. Ya in this case the logic is correct.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@siyengar thanks for the discussion tho :) This stuff is always tricky ...


return new SSLEngineResult(CLOSED, NEED_UNWRAP, bytesConsumed, bytesProduced);
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: kill line to be consistent with the case above

break;
}
packetLength -= written;
bytesConsumed += written;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure if this will help but we maybe able to reduce arithmetic operations on each loop iteration because bytesConsumed = packetLengthBefore - packetLength and it seems like we primarily need bytesConsumed at the end of the loop.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the current code is a bit cleaner and easier to understand. I can check if it makes any difference tho if you feel strong about it

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not necessary ... we can consider this as a followup PR if necessary.

SSLContext.setOptions(ctx, SSL.SSL_OP_SINGLE_ECDH_USE);
SSLContext.setOptions(ctx, SSL.SSL_OP_SINGLE_DH_USE);
SSLContext.setOptions(ctx, SSL.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
// We do not support compression as the moment so not use it.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as the moment so not use it. -> so we should explicitly disable it.


// Header (5) + Data (2^14) + Compression (1024) + Encryption (1024) + MAC (20) + Padding (256)
// Header (5) + Data (2^14) + Encryption (1024) + MAC (20) + Padding (256)
// No compression supported!

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Compression is not supported!

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Scottmitch btw do you think I should maybe factor out the disabling of compression explicitly in another PR just to make it more "clear" ?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@normanmaurer - it may be cleaner this way but it doesn't matter to me ... as long as it is disabled I'm happy.


// IMPORTANT:
//
// This calculation only works as we do not support compression and set

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This calculation only works as we do not support compression. We explicitly disable compression by setting the SSL_OP_NO_COMPRESSION option. If compression were enabled it is possible that the plain text length is > the packet length.

throw new NotSslRecordException("not an SSL/TLS record");
}

// IMPORTANT:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

consider removing this comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

but its important ;)

}
}
}
if (pendingAppData() > 0) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

now that we explicitly disable compression ... the length check up front should be good enough. I wonder if we can improve the length check to not always just require max length (not sure if that would be beneficial or not).

throw new NotSslRecordException("not an SSL/TLS record");
}

//This calculation only works as we do not support compression. We explicitly disable compression

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: add space after //

@Scottmitch Scottmitch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should let this sit in a snapshot for a few weeks before including this in a release version.

@johnou

johnou commented Dec 15, 2016

Copy link
Copy Markdown
Contributor

@normanmaurer how can I verify whether or not our game client has negotiated compression with a Netty SSL server? We are actively trying to minimize network traffic as players are complaining about data usage, how much extra work would it be to support turning compression on and off as a configuration option?

@johnou

johnou commented Dec 15, 2016

Copy link
Copy Markdown
Contributor

@Scottmitch better to get this out sooner than later as this mitigates CRIME security exploit for TLS 1.0 clients.

@normanmaurer

Copy link
Copy Markdown
Member Author

@johnou I don't think there is an easy way beside checking with wireshark. Let me factor out the "explicit" disabling of compression into another PR.

I am not sure how much extra work is needed. Would need to check in detail, but honestly its not a super high priority atm :(

@johnou

johnou commented Dec 15, 2016

Copy link
Copy Markdown
Contributor

@normanmaurer we had a quick tech meeting and decided compression is not suitable for our application (most of the messages are small and it's a time sensitive protocol so the overhead is simply not worth it).

That said I am keen to know if our client is trying to use compression because I have observed some strange errors related to parsing. I will try debugging the handshake and report back here.

@johnou

johnou commented Dec 15, 2016 •

Copy link
Copy Markdown
Contributor

@normanmaurer looks as though compression is not used in our application afterall (at least not on iPad) so we welcome this change.

Client hello:
client_hello

Server hello:
server_hello

@Scottmitch

Scottmitch commented Dec 16, 2016 •

Copy link
Copy Markdown
Member

better to get this out sooner than later as this mitigates CRIME security exploit for TLS 1.0 clients.

@johnou - Compression can be disabled via other means (it can be disabled at configure/compile time for OpenSSL). This PR is not necessary to mitigate CRIME.

@Scottmitch

Copy link
Copy Markdown
Member

how can I verify whether or not our game client has negotiated compression with a Netty SSL server?

@johnou - I'm not sure what OpenSSL library you are using or how its built, but assuming you are building it your self just disable compression at configure/compile time via no-comp [1].

If your OpenSSL library does not have compression explicitly disabled clients may still be able to negotiate compression. ssllabs can test your server for compression support [2].

[1] https://wiki.openssl.org/index.php/Compilation_and_Installation
[2] https://www.ssllabs.com/ssltest/index.html

@johnou

johnou commented Dec 16, 2016 •

Copy link
Copy Markdown
Contributor

@johnou - Compression can be disabled via other means (it can be disabled at configure/compile time for OpenSSL). This PR is not necessary to mitigate CRIME.

But still helpful.

@johnou - I'm not sure what OpenSSL library you are using or how its built, but assuming you are building it your self just disable compression at configure/compile time via no-comp [1].

Server side we are using dynamic OpenSSL artifacte with stock OS openssl package.

Client side is a little more out of our hands, we are using C# SslStream but with the ancient Mono shipped with Unity 👎

If your OpenSSL library does not have compression explicitly disabled clients may still be able to negotiate compression. ssllabs can test your server for compression support [2].

"Ports other than 443 not supported", I will look around for other services to probe our application.

https://sslanalyzer.comodoca.com does the job.

@Scottmitch

Scottmitch commented Dec 16, 2016 •

Copy link
Copy Markdown
Member

Server side we are using dynamic OpenSSL artifacte with stock OS openssl package.

Have you considered building your own. Depending on your OS/distribution the OpenSSL package may be quite old, and per this discussion you don't have control over what options are enabled.

@normanmaurer

Copy link
Copy Markdown
Member Author

@Scottmitch addressed everything... And yes I agree we should let this cook a bit before include in a release. Too risky otherwise ;)

// Write more encrypted data into the BIO. Ensure we only read one packet at a time as
// stated in the SSLEngine javadocs.
int written = writeEncryptedData(src, min(packetLengthRemaining, src.remaining()));
int written = writeEncryptedData(src, Math.min(packetLength, remaining));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAJOR Unnecessary use of fully qualified name 'Math.min' due to existing static import 'java.lang.Math.min' rule

AccessController.doPrivileged(new PrivilegedAction<Integer>() {
@Override
public Integer run() {
return Math.min(0, SystemPropertyUtil.getInt("io.netty.handler.ssl.openssl.maxBioBytes", 0));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this be Math.max, otherwise only 0 or negative values are allowed?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doh yes! Fixing

@normanmaurer

Copy link
Copy Markdown
Member Author

@Scottmitch FYI there is something wrong here... still investigate

@normanmaurer
normanmaurer force-pushed the bio_mem_size branch 2 times, most recently from 100514e to d9ffba7 Compare February 2, 2017 16:13
Motivation:

By default openssl uses 17k bytes as memory size for its BIO. This can become very wasteful if you need to handle a lot of concurrent connections. We should allow to adjust the used memory and so trade memory usage with cpu usage.

Modification:

- Allow to adjust the max memory used by the BIO
- Adjust SSLEngine implementation to not assume 17k buffers.

Result:

Its now possible to use smaller buffers when using openssl based SSLEngine.

case SSL.SSL_ERROR_ZERO_RETURN:
// This means the connection was shutdown correctly, close inbound and outbound
if (!receivedShutdown) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAJOR Refactor this code to not nest more than 5 if/for/while/switch/try statements. rule

@Scottmitch

Copy link
Copy Markdown
Member

I propose we close this in favor of #6201

@normanmaurer

Copy link
Copy Markdown
Member Author

@Scottmitch sounds good... closing now

@normanmaurer
normanmaurer deleted the bio_mem_size branch February 7, 2017 08:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants