Skip to content
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

Fix SendAsync from impersonated context with default credentials #58922

Merged
merged 5 commits into from
Sep 15, 2021
Merged
Show file tree
Hide file tree
Changes from 4 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
6 changes: 6 additions & 0 deletions src/libraries/Common/tests/System/Net/Http/LoopbackServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -866,6 +866,12 @@ public override async Task<Byte[]> ReadRequestBodyAsync()
return buffer;
}

public void CompleteRequestProcessing()
{
_contentLength = 0;
_bodyRead = false;
}

public override async Task SendResponseAsync(HttpStatusCode statusCode = HttpStatusCode.OK, IList<HttpHeaderData> headers = null, string content = "", bool isFinal = true, int requestId = 0)
{
MemoryStream headerBytes = new MemoryStream();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;

namespace System
{
public class WindowsIdentityFixture : IDisposable
{
public WindowsTestAccount TestAccount { get; private set; }

public WindowsIdentityFixture()
{
TestAccount = new WindowsTestAccount("CorFxTstWiIde01kiu");
}

public void Dispose()
{
TestAccount.Dispose();
}
}

public sealed class WindowsTestAccount : IDisposable
{
private readonly string _userName;
private SafeAccessTokenHandle _accountTokenHandle;
public SafeAccessTokenHandle AccountTokenHandle => _accountTokenHandle;
public string AccountName { get; private set; }

public WindowsTestAccount(string userName)
{
_userName = userName;
CreateUser();
}

private void CreateUser()
{
string testAccountPassword;
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
byte[] randomBytes = new byte[33];
rng.GetBytes(randomBytes);

// Add special chars to ensure it satisfies password requirements.
testAccountPassword = Convert.ToBase64String(randomBytes) + "_-As@!%*(1)4#2";

USER_INFO_1 userInfo = new USER_INFO_1
{
usri1_name = _userName,
usri1_password = testAccountPassword,
usri1_priv = 1
};

// Create user and remove/create if already exists
uint result = NetUserAdd(null, 1, ref userInfo, out uint param_err);

// error codes https://docs.microsoft.com/en-us/windows/desktop/netmgmt/network-management-error-codes
// 0 == NERR_Success
if (result == 2224) // NERR_UserExists
{
result = NetUserDel(null, userInfo.usri1_name);
if (result != 0)
{
throw new Win32Exception((int)result);
}
result = NetUserAdd(null, 1, ref userInfo, out param_err);
if (result != 0)
{
throw new Win32Exception((int)result);
}
}

const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;

if (!LogonUser(_userName, ".", testAccountPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out _accountTokenHandle))
{
_accountTokenHandle = null;
throw new Exception($"Failed to get SafeAccessTokenHandle for test account {_userName}", new Win32Exception());
}

bool gotRef = false;
try
{
_accountTokenHandle.DangerousAddRef(ref gotRef);
IntPtr logonToken = _accountTokenHandle.DangerousGetHandle();
AccountName = new WindowsIdentity(logonToken).Name;
}
finally
{
if (gotRef)
_accountTokenHandle.DangerousRelease();
}
}
}

[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool LogonUser(string userName, string domain, string password, int logonType, int logonProvider, out SafeAccessTokenHandle safeAccessTokenHandle);

[DllImport("netapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern uint NetUserAdd([MarshalAs(UnmanagedType.LPWStr)]string servername, uint level, ref USER_INFO_1 buf, out uint parm_err);

[DllImport("netapi32.dll")]
internal static extern uint NetUserDel([MarshalAs(UnmanagedType.LPWStr)]string servername, [MarshalAs(UnmanagedType.LPWStr)]string username);

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct USER_INFO_1
{
public string usri1_name;
public string usri1_password;
public uint usri1_password_age;
public uint usri1_priv;
public string usri1_home_dir;
public string usri1_comment;
public uint usri1_flags;
public string usri1_script_path;
}

public void Dispose()
{
_accountTokenHandle?.Dispose();

uint result = NetUserDel(null, _userName);

// 2221= NERR_UserNotFound
if (result != 0 && result != 2221)
{
throw new Win32Exception((int)result);
}
}
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
<Compile Include="System\PlatformDetection.cs" />
<Compile Include="System\PlatformDetection.Unix.cs" />
<Compile Include="System\PlatformDetection.Windows.cs" />
<Compile Include="System\WindowsIdentityFixture.cs" />
<!--
Interop.Library is not designed to support runtime checks therefore we are picking the Windows
variant from the Common folder and adding the missing members manually.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,6 @@ public HttpConnectionSettings()
allowHttp3 && allowHttp2 ? HttpVersion.Version30 :
allowHttp2 ? HttpVersion.Version20 :
HttpVersion.Version11;
_defaultCredentialsUsedForProxy = _proxy != null && (_proxy.Credentials == CredentialCache.DefaultCredentials || _defaultProxyCredentials == CredentialCache.DefaultCredentials);
_defaultCredentialsUsedForServer = _credentials == CredentialCache.DefaultCredentials;
}

/// <summary>Creates a copy of the settings but with some values normalized to suit the implementation.</summary>
Expand All @@ -96,8 +94,6 @@ public HttpConnectionSettings CloneAndNormalize()
_connectTimeout = _connectTimeout,
_credentials = _credentials,
_defaultProxyCredentials = _defaultProxyCredentials,
_defaultCredentialsUsedForProxy = _defaultCredentialsUsedForProxy,
_defaultCredentialsUsedForServer = _defaultCredentialsUsedForServer,
_expect100ContinueTimeout = _expect100ContinueTimeout,
_maxAutomaticRedirections = _maxAutomaticRedirections,
_maxConnectionsPerServer = _maxConnectionsPerServer,
Expand All @@ -123,6 +119,8 @@ public HttpConnectionSettings CloneAndNormalize()
_plaintextStreamFilter = _plaintextStreamFilter,
_initialHttp2StreamWindowSize = _initialHttp2StreamWindowSize,
_activityHeadersPropagator = _activityHeadersPropagator,
_defaultCredentialsUsedForProxy = _proxy != null && (_proxy.Credentials == CredentialCache.DefaultCredentials || _defaultProxyCredentials == CredentialCache.DefaultCredentials),
wfurt marked this conversation as resolved.
Show resolved Hide resolved
_defaultCredentialsUsedForServer = _credentials == CredentialCache.DefaultCredentials,
};

// TODO: Remove if/when QuicImplementationProvider is removed from System.Net.Quic.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Linq;
using System.Net.Security;
using System.Net.Test.Common;
using System.Security.Principal;
using System.Threading.Tasks;

using Xunit;
using Xunit.Abstractions;

namespace System.Net.Http.Functional.Tests
{
public class ImpersonificatedAuthTests : IClassFixture<WindowsIdentityFixture>
{
public static bool CanRunImpersonificatedTests = PlatformDetection.IsWindows && PlatformDetection.IsNotWindowsNanoServer;
private readonly WindowsIdentityFixture _fixture;
private readonly ITestOutputHelper _output;

public ImpersonificatedAuthTests(WindowsIdentityFixture windowsIdentityFixture, ITestOutputHelper output)
{
_output = output;
_fixture = windowsIdentityFixture;

Assert.False(_fixture.TestAccount.AccountTokenHandle.IsInvalid);
Assert.False(string.IsNullOrEmpty(_fixture.TestAccount.AccountName));
}

[OuterLoop]
[ConditionalTheory(nameof(CanRunImpersonificatedTests))]
[InlineData(true)]
[InlineData(false)]
[PlatformSpecific(TestPlatforms.Windows)]
public async Task DefaultHandler_ImpersonificatedUser_Success(bool useNtlm)
{
await LoopbackServer.CreateClientAndServerAsync(
async uri =>
{
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, uri);
requestMessage.Version = new Version(1, 1);

var handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;

using (var client = new HttpClient(handler))
{
HttpResponseMessage response = await client.SendAsync(requestMessage);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("foo", await response.Content.ReadAsStringAsync());

string initialUser = response.Headers.GetValues(NtAuthTests.UserHeaderName).First();

_output.WriteLine($"Starting test as {WindowsIdentity.GetCurrent().Name}");

// get token and run another request as different user.
WindowsIdentity.RunImpersonated(_fixture.TestAccount.AccountTokenHandle, () =>
{
_output.WriteLine($"Running test as {WindowsIdentity.GetCurrent().Name}");
Assert.Equal(_fixture.TestAccount.AccountName, WindowsIdentity.GetCurrent().Name);

requestMessage = new HttpRequestMessage(HttpMethod.Get, uri);
requestMessage.Version = new Version(1, 1);

HttpResponseMessage response = client.SendAsync(requestMessage).GetAwaiter().GetResult();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("foo", response.Content.ReadAsStringAsync().GetAwaiter().GetResult());

string newUser = response.Headers.GetValues(NtAuthTests.UserHeaderName).First();
Assert.Equal(_fixture.TestAccount.AccountName, newUser);
});
}
},
async server =>
{
await server.AcceptConnectionAsync(async connection =>
{
Task t = useNtlm ? NtAuthTests.HandleNtlmAuthenticationRequest(connection, closeConnection: false) : NtAuthTests.HandleNegotiateAuthenticationRequest(connection, closeConnection: false);
await t;
_output.WriteLine("Finished first request");

// Second request should use new connection as it runs as different user.
// We keep first connection open so HttpClient may be tempted top use it.
await server.AcceptConnectionAsync(async connection =>
{
Task t = useNtlm ? NtAuthTests.HandleNtlmAuthenticationRequest(connection, closeConnection: false) : NtAuthTests.HandleNegotiateAuthenticationRequest(connection, closeConnection: false);
await t;
}).ConfigureAwait(false);
}).ConfigureAwait(false);
});

}
}
}
Loading