Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<ItemGroup>
<Compile Include="$(SharedSourceRoot)SecurityHelper\**\*.cs" />
<Compile Include="$(SharedSourceRoot)RemoteAuthenticationAntiforgery.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)Buffers\RefPooledArrayBufferWriter.cs" LinkBase="Shared" />
</ItemGroup>

<ItemGroup>
Expand Down
74 changes: 67 additions & 7 deletions src/Security/Authentication/Core/src/SecureDataFormat.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers;
using System.Buffers.Text;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.WebUtilities;

namespace Microsoft.AspNetCore.Authentication;

Expand Down Expand Up @@ -42,10 +45,29 @@ public string Protect(TData data, string? purpose)
protector = protector.CreateProtector(purpose);
}

if (protector is ISpanDataProtector spanProtector)
{
return SpanProtect(spanProtector, userData);
}

var protectedData = protector.Protect(userData);
return Base64UrlTextEncoder.Encode(protectedData);
}

private static string SpanProtect(ISpanDataProtector protector, byte[] userData)
{
var writer = new RefPooledArrayBufferWriter<byte>(stackalloc byte[256]);
try
{
protector.Protect(userData, ref writer);
return WebEncoders.Base64UrlEncode(writer.WrittenSpan);
}
finally
{
writer.Dispose();
}
}

/// <inheritdoc />
public TData? Unprotect(string? protectedText)
{
Expand All @@ -62,19 +84,15 @@ public string Protect(TData data, string? purpose)
return default(TData);
}

var protectedData = Base64UrlTextEncoder.Decode(protectedText);
if (protectedData == null)
{
return default(TData);
}

var protector = _protector;
if (!string.IsNullOrEmpty(purpose))
{
protector = protector.CreateProtector(purpose);
}

var userData = protector.Unprotect(protectedData);
var userData = protector is ISpanDataProtector spanProtector
? SpanUnprotect(spanProtector, protectedText)
: Unprotect(protector, protectedText);
if (userData == null)
{
return default(TData);
Expand All @@ -88,4 +106,46 @@ public string Protect(TData data, string? purpose)
return default(TData);
}
}

private static byte[]? Unprotect(IDataProtector protector, string protectedText)
{
var protectedData = Base64UrlTextEncoder.Decode(protectedText);
if (protectedData is null)
{
return null;
}

return protector.Unprotect(protectedData);
}

private static byte[]? SpanUnprotect(ISpanDataProtector protector, string protectedText)
{
var protectedBuffer = ArrayPool<byte>.Shared.Rent(Base64Url.GetMaxDecodedLength(protectedText.Length));
try
{
if (Base64Url.DecodeFromChars(protectedText, protectedBuffer, out _, out var protectedLength) != OperationStatus.Done)
{
// Base64UrlTextEncoder.Decode also accepts standard base64, so let it handle anything that isn't strict base64url.
return Unprotect(protector, protectedText);
}

Span<byte> stackBuffer = stackalloc byte[256];
var writer = new RefPooledArrayBufferWriter<byte>(stackBuffer);
try
{
protector.Unprotect(protectedBuffer.AsSpan(0, protectedLength), ref writer);
return writer.WrittenSpan.ToArray();
}
finally
{
// Dispose clears any rented buffer; the stack buffer can also hold plaintext.
writer.Dispose();
stackBuffer.Clear();
}
}
finally
{
ArrayPool<byte>.Shared.Return(protectedBuffer);
}
}
}
84 changes: 84 additions & 0 deletions src/Security/Authentication/test/SecureDataFormatTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,90 @@ public void UnprotectWithDifferentPurposeFails()
Assert.Null(result);
}

[Fact]
public void DefaultProtectorSupportsSpans()
{
var protector = ServiceProvider.GetRequiredService<IDataProtectionProvider>().CreateProtector("test");

// The tests below rely on the default protector taking the span-based path.
Assert.IsAssignableFrom<ISpanDataProtector>(protector);
Assert.IsAssignableFrom<ISpanDataProtector>(protector.CreateProtector("purpose1"));
}

[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(15)]
[InlineData(16)]
[InlineData(17)]
[InlineData(4096)]
[InlineData(100_000)]
public void SpanAndArrayProtectorsInteroperate(int length)
{
var protector = ServiceProvider.GetRequiredService<IDataProtectionProvider>().CreateProtector("test");
var spanFormat = new SecureDataFormat<string>(new StringSerializer(), protector);
var arrayFormat = new SecureDataFormat<string>(new StringSerializer(), new ArrayOnlyDataProtector(protector));

var input = new string('a', length) + "\u00e9\u4e2d";

Assert.Equal(input, arrayFormat.Unprotect(spanFormat.Protect(input)));
Assert.Equal(input, spanFormat.Unprotect(arrayFormat.Protect(input)));
Assert.Equal(input, arrayFormat.Unprotect(spanFormat.Protect(input, "purpose1"), "purpose1"));
Assert.Equal(input, spanFormat.Unprotect(arrayFormat.Protect(input, "purpose1"), "purpose1"));
}

[Fact]
public void UnprotectAcceptsStandardBase64()
{
var protector = ServiceProvider.GetRequiredService<IDataProtectionProvider>().CreateProtector("test");
var secureDataFormat = new SecureDataFormat<string>(new StringSerializer(), protector);

var input = "abcdefghijklmnopqrstuvwxyz0123456789";
var found = false;
for (var i = 0; i < 100 && !found; i++)
{
// Ciphertext is random, so retry until the standard base64 form contains characters base64url does not allow.
var base64 = Convert.ToBase64String(protector.Protect(Encoding.UTF8.GetBytes(input)));
if (base64.AsSpan().IndexOfAny('+', '/') >= 0)
{
found = true;
Assert.Equal(input, secureDataFormat.Unprotect(base64));
}
}

Assert.True(found);
}

[Theory]
[InlineData("")]
[InlineData("a")]
[InlineData("!!!!")]
[InlineData("ab+c-d")]
[InlineData("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")]
public void UnprotectReturnsNullForInvalidInput(string protectedText)
{
var protector = ServiceProvider.GetRequiredService<IDataProtectionProvider>().CreateProtector("test");
var spanFormat = new SecureDataFormat<string>(new StringSerializer(), protector);
var arrayFormat = new SecureDataFormat<string>(new StringSerializer(), new ArrayOnlyDataProtector(protector));

Assert.Null(spanFormat.Unprotect(protectedText));
Assert.Null(arrayFormat.Unprotect(protectedText));
Assert.Null(spanFormat.Unprotect(null));
}

private class ArrayOnlyDataProtector : IDataProtector
{
private readonly IDataProtector _inner;

public ArrayOnlyDataProtector(IDataProtector inner) => _inner = inner;

public IDataProtector CreateProtector(string purpose) => new ArrayOnlyDataProtector(_inner.CreateProtector(purpose));

public byte[] Protect(byte[] plaintext) => _inner.Protect(plaintext);

public byte[] Unprotect(byte[] protectedData) => _inner.Unprotect(protectedData);
}

private class StringSerializer : IDataSerializer<string>
{
public byte[] Serialize(string model)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Security.Claims;
using BenchmarkDotNet.Attributes;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;

namespace Microsoft.AspNetCore.Security;

[MemoryDiagnoser]
public class CookieAuthenticationBenchmark
{
private IServiceProvider _services;
private IServiceScopeFactory _scopeFactory;
private string _cookieHeader;
private string _chunkedCookieHeader;

[GlobalSetup]
public void GlobalSetup()
{
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(NullLoggerFactory.Instance);
services.AddSingleton(typeof(ILogger<>), typeof(NullLogger<>));
services.AddDataProtection().UseEphemeralDataProtectionProvider();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
services.AddAuthentication().AddCookie("chunked", o => o.Cookie.Name = "Big");
_services = services.BuildServiceProvider();
_scopeFactory = _services.GetRequiredService<IServiceScopeFactory>();

_cookieHeader = SignIn(CookieAuthenticationDefaults.AuthenticationScheme, 10);
_chunkedCookieHeader = SignIn("chunked", 120);

if (!Authenticate().GetAwaiter().GetResult() || !AuthenticateChunked().GetAwaiter().GetResult())
{
throw new InvalidOperationException("Authentication failed.");
}
}

private string SignIn(string scheme, int claimCount)
{
var claims = new List<Claim> { new Claim(ClaimTypes.Name, "bob"), new Claim(ClaimTypes.NameIdentifier, "0f8fad5b-d9cb-469f-a165-70867728950e") };
for (var i = 0; i < claimCount; i++)
{
claims.Add(new Claim("custom-claim-" + i, "value-" + i + "-" + new string('x', 20)));
}
using var scope = _services.CreateScope();
var context = NewContext(scope.ServiceProvider);
context.SignInAsync(scheme, new ClaimsPrincipal(new ClaimsIdentity(claims, "test"))).GetAwaiter().GetResult();
var setCookies = context.Response.Headers.SetCookie;
return string.Join("; ", setCookies.Select(c => c.Substring(0, c.IndexOf(';'))));
}

private static DefaultHttpContext NewContext(IServiceProvider services)
{
var context = new DefaultHttpContext { RequestServices = services };
context.Request.Scheme = "https";
context.Request.Host = new HostString("localhost");
context.Request.Path = "/";
return context;
}

[Benchmark]
public async Task<bool> Authenticate()
{
await using var scope = _scopeFactory.CreateAsyncScope();
var context = NewContext(scope.ServiceProvider);
context.Request.Headers.Cookie = _cookieHeader;
var result = await context.AuthenticateAsync();
return result.Succeeded;
}

[Benchmark]
public async Task<bool> AuthenticateChunked()
{
await using var scope = _scopeFactory.CreateAsyncScope();
var context = NewContext(scope.ServiceProvider);
context.Request.Headers.Cookie = _chunkedCookieHeader;
var result = await context.AuthenticateAsync("chunked");
return result.Succeeded;
}

[Benchmark]
public async Task<bool> AuthenticateNoCookie()
{
await using var scope = _scopeFactory.CreateAsyncScope();
var context = NewContext(scope.ServiceProvider);
var result = await context.AuthenticateAsync();
return result.Succeeded;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
<ProjectReference Include="$(RepoRoot)src\Http\Http.Abstractions\src\Microsoft.AspNetCore.Http.Abstractions.csproj" />
<ProjectReference Include="$(RepoRoot)src\Http\Http.Features\src\Microsoft.AspNetCore.Http.Features.csproj" />
<ProjectReference Include="$(RepoRoot)src\Http\Http\src\Microsoft.AspNetCore.Http.csproj" />
<ProjectReference Include="$(RepoRoot)src\Http\Authentication.Core\src\Microsoft.AspNetCore.Authentication.Core.csproj" />
<ProjectReference Include="$(RepoRoot)src\DataProtection\DataProtection\src\Microsoft.AspNetCore.DataProtection.csproj" />
<ProjectReference Include="$(RepoRoot)src\Security\Authentication\Core\src\Microsoft.AspNetCore.Authentication.csproj" />
<ProjectReference Include="$(RepoRoot)src\Http\Routing\src\Microsoft.AspNetCore.Routing.csproj" />
<ProjectReference Include="$(RepoRoot)src\Security\Authentication\Cookies\src\Microsoft.AspNetCore.Authentication.Cookies.csproj" />
<ProjectReference Include="$(RepoRoot)src\Security\Authorization\Policy\src\Microsoft.AspNetCore.Authorization.Policy.csproj" />
Expand Down
56 changes: 56 additions & 0 deletions src/Security/perf/Microbenchmarks/SecureDataFormatBenchmark.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Security.Claims;
using BenchmarkDotNet.Attributes;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.DataProtection;

namespace Microsoft.AspNetCore.Security;

[MemoryDiagnoser]
public class SecureDataFormatBenchmark
{
private TicketDataFormat _format;
private AuthenticationTicket _ticket;
private string _protectedTicket;

[Params(7, 100)]
public int ClaimCount { get; set; }

[GlobalSetup]
public void GlobalSetup()
{
var protector = new EphemeralDataProtectionProvider().CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Cookies", "v2");
_format = new TicketDataFormat(protector);

var identity = new ClaimsIdentity("Identity.Application");
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "0f8fad5b-d9cb-469f-a165-70867728950e"));
identity.AddClaim(new Claim(ClaimTypes.Name, "bob@contoso.com"));
identity.AddClaim(new Claim("AspNet.Identity.SecurityStamp", "MUFAS2EV5RQ5ZGCCIUFQVCIPRUZQ5JWK"));
for (var i = 3; i < ClaimCount; i++)
{
identity.AddClaim(new Claim(ClaimTypes.Role, "role-" + i));
}

var properties = new AuthenticationProperties
{
IssuedUtc = new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero),
ExpiresUtc = new DateTimeOffset(2025, 1, 15, 0, 0, 0, TimeSpan.Zero),
IsPersistent = true,
};
_ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), properties, "Identity.Application");
_protectedTicket = _format.Protect(_ticket);

if (_format.Unprotect(_protectedTicket) is null)
{
throw new InvalidOperationException("Round trip failed.");
}
}

[Benchmark]
public string Protect() => _format.Protect(_ticket);

[Benchmark]
public AuthenticationTicket Unprotect() => _format.Unprotect(_protectedTicket);
}
2 changes: 1 addition & 1 deletion src/Shared/Buffers/RefPooledArrayBufferWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ private void CheckAndResizeBuffer(int sizeHint)

var previousBuffer = oldBuffer.AsSpan(0, _index);
previousBuffer.CopyTo(_rentedBuffer);
ArrayPool<T>.Shared.Return(oldBuffer);
ArrayPool<T>.Shared.Return(oldBuffer, clearArray: true);

_buffer = _rentedBuffer;

Expand Down
Loading