Files
swift-nio-http2/Sources/NIOHTTP2/HTTP2ConnectionStateChange.swift
T
Cory Benfield 86ce1dcd0d Merge pull request from GHSA-jchv-x857-q8fq
* Forbid excessive sending of empty DATA frames

Motivation:

One vector for DoS can be sending a large number of essentially "empty"
frames, such as empty DATA frames without END_STREAM set. We should
forbid peers from doing so excessively, but we want to tolerate
implementations that occasionally emit such a frame for buggy reasons.

Modifications:

- Added verification that too many empty DATA frames are not sent.

Result:

Better resistance to DoS attacks.

* Improved buffering in CompoundOutboundBuffer

Motivation:

In HTTP/2 it is possible for remote peers to submit work in a way that
cause the NIOHTTP2Handler to generate a substantial number of control
frames. If the peer is not consuming these frames, we can eventually run
out of memory and die, which is not exactly ideal.

It's hard for us to know how the buffering is going if we always submit
all frames directly to the Channel, so we need to pay attention to
whether the Channel is actually writable. If it isn't, rather than issue
further writes we need to delay those writes so we can keep track of how
big that buffer is getting. If the buffer gets too large we need a
circuit breaker to drop the connection, as we're clearly not able to get
work done.

This patch adds a new buffer for outbound control frames. This new
buffer is the last step in the buffering sequence, and the first to be
drained when a Channel becomes writable.

Additionally, enhancements need to be made to ensure that other buffers
behave correctly in the face of this new model. The
ConcurrentStreamsBuffer needs to be more aggressive about storing
HEADERS frames that cannot be emitted to the wire because it does not
tolerate emitting a HEADERS frame that cannot be immediately written to
the wire. Additionally, the buffers must not be polled when a Channel is
unwritable.

This is a large patch, but it does substantially change the buffering
logic, and protects NIO against a wide range of denial of service
attacks, while providing a clear and coherent defense surface.

Note that one thing this patch does not do is constrain the size of the
buffers in the ConcurrentStreamsBuffer. This is on purpose: the size of
this buffer is controlled entirely by user action. Users that do not
wish to buffer excessively in this buffer can avoid doing so simply by
respecting the peer's value of SETTINGS_MAX_CONCURRENT_STREAMS. As the
entire purpose of this buffer is to tolerate users that do not wish to
abide by this setting, it would be unreasonable to provide an upper
bound on the value used in this setting.

Modifications:

- Moved the various buffers into a directory.
- Built and implemented ControlFrameBuffer.
- Integrated ControlFrameBuffer into CompoundOutboundBuffer.
- Added awareness around channel writability to HTTP2Handler
- Enhanced ConcurrentStreamsBuffer to be writability-aware.

Result:

We'll have somewhere to put control frames.

* Cleanup API for merged security fixes.

Motivation:

After merging the security fixes we ended up with a slightly awkward
API: the argument names differed slightly for no good reason, and it
became impossible to override only one of the two security settings.

Modifications:

- Renamed `max` to `maximum`.
- Gave default values for the security settings.

Result:

Better user experience.

* Prevent DoS with large header lists.

Motivation:

There are two ways malicious peers could attempt to DoS a SwiftNIO
HTTP/2 implementation with header lists. The first would be to attempt
to send an enormous header list, ideally with an amplification factor.
This approach was possible because SwiftNIO never actually enforced the
value of the max header list size it advertised.

In principle the peer can still get a good amplification attack effect
by sending a long header list that contains zero-length headers. We may
as well close this door as well: zero length header field names are
unacceptable, and so we should forbid them.

Modifications:

- Added max header list enforcement.
- Forbade zero-length header field names.

Result:

Peers cannot DoS a SwiftNIO HTTP/2 implementation using large header
lists.
2019-08-13 18:00:41 +01:00

214 lines
9.0 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// An `NIOHTTP2ConnectionStateChange` provides information about the state change
/// that occurred as a result of a single frame being sent or received.
///
/// This enumeration allows users to avoid needing to replicate the complete HTTP/2
/// state machine. Instead, users can use this enumeration to determine the new state
/// of the connection and affected streams.
internal enum NIOHTTP2ConnectionStateChange: Hashable {
/// A stream has been created.
case streamCreated(StreamCreated)
/// A stream has been closed.
case streamClosed(StreamClosed)
/// A stream was created and then immediately closed. This can happen when a stream reserved
/// via PUSH_PROMISE has a HEADERS frame with END_STREAM sent on it by the server.
case streamCreatedAndClosed(StreamCreatedAndClosed)
/// A frame was sent or received that changes some flow control windows.
case flowControlChange(FlowControlChange)
/// Multiple streams have been closed. This happens as a result of a GOAWAY frame
/// being sent or received.
case bulkStreamClosure(BulkStreamClosure)
/// The remote peer's settings have been changed.
case remoteSettingsChanged(RemoteSettingsChanged)
/// The local peer's settings have been changed.
case localSettingsChanged(LocalSettingsChanged)
/// A stream has been created.
internal struct StreamCreated: Hashable {
internal var streamID: HTTP2StreamID
/// The initial local stream window size. This may be nil if there is no local stream window.
/// This occurs if the stream has been pushed by the remote peer, in which case we will never be able
/// to send on it.
internal var localStreamWindowSize: Int?
/// The initial remote stream window size. This may be nil if there is no remote stream window.
/// This occurs if the stream has been pushed by the local peer, in which case tje remote peer will never be able
/// to send on it.
internal var remoteStreamWindowSize: Int?
internal init(streamID: HTTP2StreamID, localStreamWindowSize: Int?, remoteStreamWindowSize: Int?) {
self.streamID = streamID
self.localStreamWindowSize = localStreamWindowSize
self.remoteStreamWindowSize = remoteStreamWindowSize
}
}
/// A stream has been closed.
internal struct StreamClosed: Hashable {
internal var streamID: HTTP2StreamID
internal var localConnectionWindowSize: Int
internal var remoteConnectionWindowSize: Int
internal var reason: HTTP2ErrorCode?
internal init(streamID: HTTP2StreamID, localConnectionWindowSize: Int, remoteConnectionWindowSize: Int, reason: HTTP2ErrorCode?) {
self.streamID = streamID
self.localConnectionWindowSize = localConnectionWindowSize
self.remoteConnectionWindowSize = remoteConnectionWindowSize
self.reason = reason
}
}
/// A stream has been created and immediately closed. In this case, the only relevant bit of information
/// is the stream ID: flow control windows are not relevant as this frame is not flow controlled and does
/// not change window sizes.
internal struct StreamCreatedAndClosed: Hashable {
internal var streamID: HTTP2StreamID
internal init(streamID: HTTP2StreamID) {
self.streamID = streamID
}
}
/// A flow control window has changed.
///
/// A change to a flow control window may affect the connection window and optionally
/// may also affect a stream window. This occurs due to the sending or receiving of
/// a flow controlled frame or a window update frame. Flow controlled frames change
/// both the connection and stream window sizes: window update frames change
/// only one. To avoid ambiguity, we report the current window size of the connection
/// on all such events, and the relevant stream if there is one (which there usually is).
internal struct FlowControlChange: Hashable {
internal var localConnectionWindowSize: Int
internal var remoteConnectionWindowSize: Int
internal var localStreamWindowSize: StreamWindowSizeChange?
/// The information about the stream window size. Either the local or remote
/// stream window information may be nil, if there is no flow control window
/// for that direction (e.g. if the stream is half-closed).
internal struct StreamWindowSizeChange: Hashable {
internal var streamID: HTTP2StreamID
internal var localStreamWindowSize: Int?
internal var remoteStreamWindowSize: Int?
internal init(streamID: HTTP2StreamID, localStreamWindowSize: Int?, remoteStreamWindowSize: Int?) {
self.streamID = streamID
self.localStreamWindowSize = localStreamWindowSize
self.remoteStreamWindowSize = remoteStreamWindowSize
}
}
internal init(localConnectionWindowSize: Int, remoteConnectionWindowSize: Int, localStreamWindowSize: StreamWindowSizeChange?) {
self.localConnectionWindowSize = localConnectionWindowSize
self.remoteConnectionWindowSize = remoteConnectionWindowSize
self.localStreamWindowSize = localStreamWindowSize
}
}
/// A large number of streams have been closed at once.
internal struct BulkStreamClosure: Hashable {
internal var closedStreams: [HTTP2StreamID]
internal init(closedStreams: [HTTP2StreamID]) {
self.closedStreams = closedStreams
}
}
/// The remote peer's settings have changed in a way that is not trivial to decode.
///
/// This object keeps track of the change on all stream window sizes via
/// SETTINGS frame.
internal struct RemoteSettingsChanged: Hashable {
internal var streamWindowSizeChange: Int = 0
internal var newMaxFrameSize: UInt32?
internal var newMaxConcurrentStreams: UInt32?
}
/// The local peer's settings have changed in a way that is not trivial to decode.
///
/// This object keeps track of the change on all stream window sizes via
/// SETTINGS frame.
internal struct LocalSettingsChanged: Hashable {
internal var streamWindowSizeChange: Int = 0
internal var newMaxFrameSize: UInt32?
internal var newMaxHeaderListSize: UInt32?
}
}
/// A representation of a state change at the level of a single stream.
///
/// While the NIOHTTP2ConnectionStateChange is an object that affects an entire connection,
/// it is more accurately the composition of an effect on a single stream and a wider effect on a
/// connection. This object encapsulates the effect on a single stream, and can be used along with
/// other information to bootstrap a NIOHTTP2ConnectionStateChange.
///
/// Where possible, this object uses the structures from NIOHTTP2ConnectionStateChange. Where not possible
/// it defines its own.
internal enum StreamStateChange: Hashable {
case streamCreated(NIOHTTP2ConnectionStateChange.StreamCreated)
case streamClosed(StreamClosed)
case windowSizeChange(NIOHTTP2ConnectionStateChange.FlowControlChange.StreamWindowSizeChange)
case streamCreatedAndClosed(NIOHTTP2ConnectionStateChange.StreamCreatedAndClosed)
struct StreamClosed: Hashable {
var streamID: HTTP2StreamID
var reason: HTTP2ErrorCode?
}
}
internal extension NIOHTTP2ConnectionStateChange {
init<ConnectionState: HasFlowControlWindows>(_ streamChange: StreamStateChange, connectionState: ConnectionState) {
switch streamChange {
case .streamClosed(let streamClosedState):
self = .streamClosed(.init(streamID: streamClosedState.streamID,
localConnectionWindowSize: Int(connectionState.outboundFlowControlWindow),
remoteConnectionWindowSize: Int(connectionState.inboundFlowControlWindow),
reason: streamClosedState.reason))
case .streamCreated(let streamCreated):
self = .streamCreated(streamCreated)
case .streamCreatedAndClosed(let streamCreatedAndClosed):
self = .streamCreatedAndClosed(streamCreatedAndClosed)
case .windowSizeChange(let streamSizeChange):
self = .flowControlChange(.init(localConnectionWindowSize: Int(connectionState.outboundFlowControlWindow),
remoteConnectionWindowSize: Int(connectionState.inboundFlowControlWindow),
localStreamWindowSize: streamSizeChange))
}
}
}