Skip to content

Fix for CRLF injection vulnerability (copy commit 483b1d8d from main) #1955

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: rel/v5.2
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions Refit.Tests/AuthenticatedClientHandlerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ public interface IMyAuthenticatedService
Task<string> GetAuthenticated();
}

public interface IInheritedAuthenticatedServiceWithHeadersCRLF //: IAuthenticatedServiceWithHeaders
{
[Get("/get-inherited-thing\r\n\r\nGET /smuggled")]
Task<string> GetInheritedThing();
}


[Fact]
public void DefaultHandlerIsHttpClientHandler()
Expand Down Expand Up @@ -120,5 +126,31 @@ public async void AuthenticatedHandlerWithParamUsesAuth()

Assert.Equal("Ok", result);
}

[Fact]
public async void AuthentictedMethodFromInheritedClassWithHeadersAttributeUsesAuth_WithCRLFCheck()
{
var handler = new MockHttpMessageHandler();
var settings = new RefitSettings()
{
AuthorizationHeaderValueGetter = () => Task.FromResult("tokenValue"),
HttpMessageHandlerFactory = () => handler,
};

handler
.Expect(HttpMethod.Get, "http://api/get-inherited-thing")
.WithHeaders("Authorization", "Bearer tokenValue")
.Respond("text/plain", "Ok");

await Assert.ThrowsAsync<ArgumentException>(async () =>
{
var fixture = RestService.For<IInheritedAuthenticatedServiceWithHeadersCRLF>(
"http://api",
settings
);

var result = await fixture.GetInheritedThing();
});
}
}
}
40 changes: 40 additions & 0 deletions Refit.Tests/RefitStubs.Net46.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1793,6 +1793,46 @@ Task<ApiResponse<HttpContent>> IHttpContentApi.PostFileUploadWithMetadata(HttpCo
}
}

namespace Refit.Tests
{
using global::System;
using global::System.Collections.Generic;
using global::System.Net;
using global::System.Net.Http;
using global::System.Text;
using global::System.Threading.Tasks;
using global::RichardSzalay.MockHttp;
using global::Refit;
using global::Xunit;

/// <inheritdoc />
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[global::System.Diagnostics.DebuggerNonUserCode]
[Preserve]
[global::System.Reflection.Obfuscation(Exclude=true)]
partial class AutoGeneratedAuthenticatedClientHandlerTestsIInheritedAuthenticatedServiceWithHeadersCRLF : AuthenticatedClientHandlerTests.IInheritedAuthenticatedServiceWithHeadersCRLF
{
/// <inheritdoc />
public HttpClient Client { get; protected set; }
readonly IRequestBuilder requestBuilder;

/// <inheritdoc />
public AutoGeneratedAuthenticatedClientHandlerTestsIInheritedAuthenticatedServiceWithHeadersCRLF(HttpClient client, IRequestBuilder requestBuilder)
{
Client = client;
this.requestBuilder = requestBuilder;
}

/// <inheritdoc />
Task<string> AuthenticatedClientHandlerTests.IInheritedAuthenticatedServiceWithHeadersCRLF.GetInheritedThing()
{
var arguments = new object[] { };
var func = requestBuilder.BuildRestResultFuncForMethod("GetInheritedThing", new Type[] { });
return (Task<string>)func(Client, arguments);
}
}
}

namespace Refit.Tests
{
using global::System;
Expand Down
40 changes: 40 additions & 0 deletions Refit.Tests/RefitStubs.NetCore2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1793,6 +1793,46 @@ Task<ApiResponse<HttpContent>> IHttpContentApi.PostFileUploadWithMetadata(HttpCo
}
}

namespace Refit.Tests
{
using global::System;
using global::System.Collections.Generic;
using global::System.Net;
using global::System.Net.Http;
using global::System.Text;
using global::System.Threading.Tasks;
using global::RichardSzalay.MockHttp;
using global::Refit;
using global::Xunit;

/// <inheritdoc />
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[global::System.Diagnostics.DebuggerNonUserCode]
[Preserve]
[global::System.Reflection.Obfuscation(Exclude=true)]
partial class AutoGeneratedAuthenticatedClientHandlerTestsIInheritedAuthenticatedServiceWithHeadersCRLF : AuthenticatedClientHandlerTests.IInheritedAuthenticatedServiceWithHeadersCRLF
{
/// <inheritdoc />
public HttpClient Client { get; protected set; }
readonly IRequestBuilder requestBuilder;

/// <inheritdoc />
public AutoGeneratedAuthenticatedClientHandlerTestsIInheritedAuthenticatedServiceWithHeadersCRLF(HttpClient client, IRequestBuilder requestBuilder)
{
Client = client;
this.requestBuilder = requestBuilder;
}

/// <inheritdoc />
Task<string> AuthenticatedClientHandlerTests.IInheritedAuthenticatedServiceWithHeadersCRLF.GetInheritedThing()
{
var arguments = new object[] { };
var func = requestBuilder.BuildRestResultFuncForMethod("GetInheritedThing", new Type[] { });
return (Task<string>)func(Client, arguments);
}
}
}

namespace Refit.Tests
{
using global::System;
Expand Down
40 changes: 40 additions & 0 deletions Refit.Tests/RefitStubs.NetCore3.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1793,6 +1793,46 @@ Task<ApiResponse<HttpContent>> IHttpContentApi.PostFileUploadWithMetadata(HttpCo
}
}

namespace Refit.Tests
{
using global::System;
using global::System.Collections.Generic;
using global::System.Net;
using global::System.Net.Http;
using global::System.Text;
using global::System.Threading.Tasks;
using global::RichardSzalay.MockHttp;
using global::Refit;
using global::Xunit;

/// <inheritdoc />
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[global::System.Diagnostics.DebuggerNonUserCode]
[Preserve]
[global::System.Reflection.Obfuscation(Exclude=true)]
partial class AutoGeneratedAuthenticatedClientHandlerTestsIInheritedAuthenticatedServiceWithHeadersCRLF : AuthenticatedClientHandlerTests.IInheritedAuthenticatedServiceWithHeadersCRLF
{
/// <inheritdoc />
public HttpClient Client { get; protected set; }
readonly IRequestBuilder requestBuilder;

/// <inheritdoc />
public AutoGeneratedAuthenticatedClientHandlerTestsIInheritedAuthenticatedServiceWithHeadersCRLF(HttpClient client, IRequestBuilder requestBuilder)
{
Client = client;
this.requestBuilder = requestBuilder;
}

/// <inheritdoc />
Task<string> AuthenticatedClientHandlerTests.IInheritedAuthenticatedServiceWithHeadersCRLF.GetInheritedThing()
{
var arguments = new object[] { };
var func = requestBuilder.BuildRestResultFuncForMethod("GetInheritedThing", new Type[] { });
return (Task<string>)func(Client, arguments);
}
}
}

namespace Refit.Tests
{
using global::System;
Expand Down
12 changes: 12 additions & 0 deletions Refit/RequestBuilderImplementation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -853,6 +853,10 @@ static void SetHeader(HttpRequestMessage request, string name, string value)

if (value == null) return;

// CRLF injection protection
name = EnsureSafe(name);
value = EnsureSafe(value);

var added = request.Headers.TryAddWithoutValidation(name, value);

// Don't even bother trying to add the header as a content header
Expand All @@ -862,5 +866,13 @@ static void SetHeader(HttpRequestMessage request, string name, string value)
request.Content.Headers.TryAddWithoutValidation(name, value);
}
}

static string EnsureSafe(string value)
{
// Remove CR and LF characters
#pragma warning disable CA1307 // Specify StringComparison for clarity
return value.Replace("\r", string.Empty).Replace("\n", string.Empty);
#pragma warning restore CA1307 // Specify StringComparison for clarity
}
}
}
6 changes: 6 additions & 0 deletions Refit/RestMethodInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,12 @@ void VerifyUrlPathIsSane(string relativePath)

if (!relativePath.StartsWith("/"))
throw new ArgumentException($"URL path {relativePath} must start with '/' and be of the form '/foo/bar/baz'");

// CRLF injection protection
if (relativePath.Contains("\r") || relativePath.Contains("\n"))
throw new ArgumentException(
$"URL path {relativePath} must not contain CR or LF characters"
);
}

Dictionary<int, RestMethodParameterInfo> BuildParameterMap(string relativePath, List<ParameterInfo> parameterInfo)
Expand Down
Loading