diff options
author | GitLab Bot <gitlab-bot@gitlab.com> | 2020-10-21 07:08:36 +0000 |
---|---|---|
committer | GitLab Bot <gitlab-bot@gitlab.com> | 2020-10-21 07:08:36 +0000 |
commit | 48aff82709769b098321c738f3444b9bdaa694c6 (patch) | |
tree | e00c7c43e2d9b603a5a6af576b1685e400410dee /lib/gitlab/middleware/handle_null_bytes.rb | |
parent | 879f5329ee916a948223f8f43d77fba4da6cd028 (diff) | |
download | gitlab-ce-48aff82709769b098321c738f3444b9bdaa694c6.tar.gz |
Add latest changes from gitlab-org/gitlab@13-5-stable-eev13.5.0-rc42
Diffstat (limited to 'lib/gitlab/middleware/handle_null_bytes.rb')
-rw-r--r-- | lib/gitlab/middleware/handle_null_bytes.rb | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/lib/gitlab/middleware/handle_null_bytes.rb b/lib/gitlab/middleware/handle_null_bytes.rb new file mode 100644 index 00000000000..c88dfb6ee0b --- /dev/null +++ b/lib/gitlab/middleware/handle_null_bytes.rb @@ -0,0 +1,61 @@ +# frozen_string_literal: true + +module Gitlab + module Middleware + # There is no valid reason for a request to contain a null byte (U+0000) + # so just return HTTP 400 (Bad Request) if we receive one + class HandleNullBytes + NULL_BYTE_REGEX = Regexp.new(Regexp.escape("\u0000")).freeze + + attr_reader :app + + def initialize(app) + @app = app + end + + def call(env) + return [400, {}, ["Bad Request"]] if request_has_null_byte?(env) + + app.call(env) + end + + private + + def request_has_null_byte?(request) + return false if ENV['REJECT_NULL_BYTES'] == "1" + + request = Rack::Request.new(request) + + request.params.values.any? do |value| + param_has_null_byte?(value) + end + end + + def param_has_null_byte?(value, depth = 0) + # Guard against possible attack sending large amounts of nested params + # Should be safe as deeply nested params are highly uncommon. + return false if depth > 2 + + depth += 1 + + if value.respond_to?(:match) + string_contains_null_byte?(value) + elsif value.respond_to?(:values) + value.values.any? do |hash_value| + param_has_null_byte?(hash_value, depth) + end + elsif value.is_a?(Array) + value.any? do |array_value| + param_has_null_byte?(array_value, depth) + end + else + false + end + end + + def string_contains_null_byte?(string) + string.match?(NULL_BYTE_REGEX) + end + end + end +end |