Files
swift-nio-http2/Sources/NIOHTTP2/HTTP2Error.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

305 lines
9.4 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 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 NIOHPACK
public protocol NIOHTTP2Error: Equatable, Error { }
/// Errors that NIO raises when handling HTTP/2 connections.
public enum NIOHTTP2Errors {
/// The outbound frame buffers have become filled, and it is not possible to buffer
/// further outbound frames. This occurs when the remote peer is generating work
/// faster than they are consuming the result. Additional buffering runs the risk of
/// memory exhaustion.
public struct ExcessiveOutboundFrameBuffering: NIOHTTP2Error {
public init() { }
}
/// NIO's upgrade handler encountered a successful upgrade to a protocol that it
/// does not recognise.
public struct InvalidALPNToken: NIOHTTP2Error {
public init() { }
}
/// An attempt was made to issue a write on a stream that does not exist.
public struct NoSuchStream: NIOHTTP2Error {
/// The stream ID that was used that does not exist.
public var streamID: HTTP2StreamID
public init(streamID: HTTP2StreamID) {
self.streamID = streamID
}
}
/// A stream was closed.
public struct StreamClosed: NIOHTTP2Error {
/// The stream ID that was closed.
public var streamID: HTTP2StreamID
/// The error code associated with the closure.
public var errorCode: HTTP2ErrorCode
public init(streamID: HTTP2StreamID, errorCode: HTTP2ErrorCode) {
self.streamID = streamID
self.errorCode = errorCode
}
}
public struct BadClientMagic: NIOHTTP2Error {
public init() {}
}
/// A stream state transition was attempted that was not valid.
public struct BadStreamStateTransition: NIOHTTP2Error {
public init() { }
}
/// An attempt was made to change the flow control window size, either via
/// SETTINGS or WINDOW_UPDATE, but this change would move the flow control
/// window size out of bounds.
public struct InvalidFlowControlWindowSize: NIOHTTP2Error {
/// The delta being applied to the flow control window.
public var delta: Int
/// The size of the flow control window before the delta was applied.
public var currentWindowSize: Int
public init(delta: Int, currentWindowSize: Int) {
self.delta = delta
self.currentWindowSize = currentWindowSize
}
}
/// A frame was sent or received that violates HTTP/2 flow control rules.
public struct FlowControlViolation: NIOHTTP2Error {
public init() { }
}
/// A SETTINGS frame was sent or received with an invalid setting.
public struct InvalidSetting: NIOHTTP2Error {
/// The invalid setting.
public var setting: HTTP2Setting
public init(setting: HTTP2Setting) {
self.setting = setting
}
}
/// An attempt to perform I/O was made on a connection that is already closed.
public struct IOOnClosedConnection: NIOHTTP2Error {
public init() { }
}
/// A SETTINGS frame was received that is invalid.
public struct ReceivedBadSettings: NIOHTTP2Error {
public init() { }
}
/// A violation of SETTINGS_MAX_CONCURRENT_STREAMS occurred.
public struct MaxStreamsViolation: NIOHTTP2Error {
public init() { }
}
/// An attempt was made to use a stream ID that is too small.
public struct StreamIDTooSmall: NIOHTTP2Error {
public init() { }
}
/// An attempt was made to send a frame without having previously sent a connection preface!
public struct MissingPreface: NIOHTTP2Error {
public init() { }
}
/// An attempt was made to create a stream after a GOAWAY frame has forbidden further
/// stream creation.
public struct CreatedStreamAfterGoaway: NIOHTTP2Error {
public init() { }
}
/// A peer has attempted to create a stream with a stream ID it is not permitted to use.
public struct InvalidStreamIDForPeer: NIOHTTP2Error {
public init() { }
}
/// An attempt was made to send a new GOAWAY frame whose lastStreamID is higher than the previous value.
public struct RaisedGoawayLastStreamID: NIOHTTP2Error {
public init() { }
}
/// The size of the window increment is invalid.
public struct InvalidWindowIncrementSize: NIOHTTP2Error {
public init() { }
}
/// An attempt was made to push a stream, even though the settings forbid it.
public struct PushInViolationOfSetting: NIOHTTP2Error {
public init() { }
}
/// An attempt was made to use a currently unsupported feature.
public struct Unsupported: NIOHTTP2Error {
public var info: String
public init(info: String) {
self.info = info
}
}
public struct UnableToSerializeFrame: NIOHTTP2Error {
public init() { }
}
public struct UnableToParseFrame: NIOHTTP2Error {
public init() { }
}
/// A pseudo-header field is missing.
public struct MissingPseudoHeader: NIOHTTP2Error {
public var name: String
public init(_ name: String) {
self.name = name
}
}
/// A pseudo-header field has been duplicated.
public struct DuplicatePseudoHeader: NIOHTTP2Error {
public var name: String
public init(_ name: String) {
self.name = name
}
}
/// A header block contained a pseudo-header after a regular header.
public struct PseudoHeaderAfterRegularHeader: NIOHTTP2Error {
public var name: String
public init(_ name: String) {
self.name = name
}
}
/// An unknown pseudo-header was received.
public struct UnknownPseudoHeader: NIOHTTP2Error {
public var name: String
public init(_ name: String) {
self.name = name
}
}
/// A header block was received with an invalid set of pseudo-headers for the block type.
public struct InvalidPseudoHeaders: NIOHTTP2Error {
public var headerBlock: HPACKHeaders
public init(_ block: HPACKHeaders) {
self.headerBlock = block
}
}
/// An outbound request was about to be sent, but does not contain a Host header.
public struct MissingHostHeader: NIOHTTP2Error {
public init() { }
}
/// An outbound request was about to be sent, but it contains a duplicated Host header.
public struct DuplicateHostHeader: NIOHTTP2Error {
public init() { }
}
/// A HTTP/2 header block was received with an empty :path header.
public struct EmptyPathHeader: NIOHTTP2Error {
public init() { }
}
/// A :status header was received with an invalid value.
public struct InvalidStatusValue: NIOHTTP2Error {
public var value: String
public init(_ value: String) {
self.value = value
}
}
/// A priority update was received that would create a PRIORITY cycle.
public struct PriorityCycle: NIOHTTP2Error {
/// The affected stream ID.
public var streamID: HTTP2StreamID
public init(streamID: HTTP2StreamID) {
self.streamID = streamID
}
}
/// An attempt was made to send trailers without setting END_STREAM on them.
public struct TrailersWithoutEndStream: NIOHTTP2Error {
/// The affected stream ID.
public var streamID: HTTP2StreamID
public init(streamID: HTTP2StreamID) {
self.streamID = streamID
}
}
/// An attempt was made to send a header field with a field name that is not valid in HTTP/2.
public struct InvalidHTTP2HeaderFieldName: NIOHTTP2Error {
public var fieldName: String
public init(_ fieldName: String) {
self.fieldName = fieldName
}
}
/// Connection-specific header fields are forbidden in HTTP/2: this error is raised when one is
/// sent or received.
public struct ForbiddenHeaderField: NIOHTTP2Error {
public var name: String
public var value: String
public init(name: String, value: String) {
self.name = name
self.value = value
}
}
/// A request or response has violated the expected content length, either exceeding or falling beneath it.
public struct ContentLengthViolated: NIOHTTP2Error {
public init() { }
}
/// The remote peer has sent an excessive number of empty DATA frames, which looks like a denial of service
/// attempt, so the connection has been closed.
public struct ExcessiveEmptyDataFrames: NIOHTTP2Error {
public init() { }
}
/// The remote peer has sent a header block so large that NIO refuses to buffer any more data than that.
public struct ExcessivelyLargeHeaderBlock: NIOHTTP2Error {
public init() { }
}
}
/// This enum covers errors that are thrown internally for messaging reasons. These should
/// not leak.
internal enum InternalError: Error {
case attemptedToCreateStream
case codecError(code: HTTP2ErrorCode)
}
extension InternalError: Hashable { }