mirror of
https://github.com/apple/swift-nio-http2
synced 2026-11-24 04:38:00 +00:00
* 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.
109 lines
4.6 KiB
Swift
109 lines
4.6 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
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
import NIO
|
|
|
|
|
|
/// A buffer that stores outbound control frames.
|
|
///
|
|
/// In general it is preferential to buffer outbound frames instead of passing them into the channel.
|
|
/// This is because once the frame has left the HTTP2 handler and moved into the Channel it is no longer
|
|
/// easy for us to tell how much data has been buffered. The larger the buffer grows, the more likely it
|
|
/// is that the peer is consuming resources of ours that we need for other use-cases, and in some cases
|
|
/// this may amount to an actual denial of service attack.
|
|
///
|
|
/// We have a number of buffers that handle data frames, but a similar concern applies to control frames
|
|
/// too. Control frames need to be emitted with relatively high priority, but they should only be emitted
|
|
/// when it will be reasonably possible to write them to the network. As long as it is not possible, we
|
|
/// want to store them where we can see them, and use the buffer size to make choices about the connection.
|
|
struct ControlFrameBuffer {
|
|
/// Any control frame writes that may need to be emitted.
|
|
private var pendingControlFrames: MarkedCircularBuffer<PendingControlFrame>
|
|
|
|
/// The maximum size of the buffer. If we have to buffer more frames than this,
|
|
/// we'll kill the connection.
|
|
internal var maximumBufferSize: Int
|
|
}
|
|
|
|
|
|
// MARK:- ControlFrameBuffer initializers
|
|
extension ControlFrameBuffer {
|
|
internal init(maximumBufferSize: Int) {
|
|
// We allocate a circular buffer of reasonable size to ensure that if we ever do have to
|
|
// buffer control frames that we won't need to resize this too aggressively.
|
|
self.pendingControlFrames = MarkedCircularBuffer(initialCapacity: 16)
|
|
self.maximumBufferSize = maximumBufferSize
|
|
}
|
|
}
|
|
|
|
|
|
// MARK:- ControlFrameBuffer frame processing
|
|
extension ControlFrameBuffer {
|
|
internal mutating func processOutboundFrame(_ frame: HTTP2Frame, promise: EventLoopPromise<Void>?, channelWritable: Bool) throws -> OutboundFrameAction {
|
|
switch frame.payload {
|
|
case .data:
|
|
// These frames are not buffered here. If it reached us, it's because we believe the channel is writable,
|
|
// and we must have no control frames buffered.
|
|
assert(channelWritable, "Received flushed data frame without writable channel")
|
|
assert(self.pendingControlFrames.count == 0, "Received flush data frames while buffering control frames")
|
|
return .forward
|
|
default:
|
|
// Control frames. These are what we buffer. We buffer them in two cases: either we have something else
|
|
// already buffered (to ensure ordering stays correct), or the channel isn't writable.
|
|
if !channelWritable || self.pendingControlFrames.count > 0 {
|
|
try self.bufferFrame(frame, promise: promise)
|
|
return .nothing
|
|
} else {
|
|
return .forward
|
|
}
|
|
}
|
|
}
|
|
|
|
internal mutating func flushReceived() {
|
|
self.pendingControlFrames.mark()
|
|
}
|
|
|
|
internal mutating func nextFlushedWritableFrame() -> PendingControlFrame? {
|
|
if self.pendingControlFrames.hasMark && self.pendingControlFrames.count > 0 {
|
|
return self.pendingControlFrames.removeFirst()
|
|
} else {
|
|
return nil
|
|
}
|
|
}
|
|
|
|
internal func invalidateBuffer(reason: ChannelError) {
|
|
for write in self.pendingControlFrames {
|
|
write.promise?.fail(reason)
|
|
}
|
|
}
|
|
|
|
private mutating func bufferFrame(_ frame: HTTP2Frame, promise: EventLoopPromise<Void>?) throws {
|
|
guard self.pendingControlFrames.count < self.maximumBufferSize else {
|
|
// Appending another frame would violate the maximum buffer size. We're storing too many frames here,
|
|
// we gotta move on.
|
|
throw NIOHTTP2Errors.ExcessiveOutboundFrameBuffering()
|
|
}
|
|
self.pendingControlFrames.append(PendingControlFrame(frame: frame, promise: promise))
|
|
}
|
|
}
|
|
|
|
|
|
// MARK:- ControlFrameBuffer.PendingControlFrame definition
|
|
extension ControlFrameBuffer {
|
|
/// A buffered control frame write and its associated promise.
|
|
struct PendingControlFrame {
|
|
var frame: HTTP2Frame
|
|
var promise: EventLoopPromise<Void>?
|
|
}
|
|
}
|