-
Notifications
You must be signed in to change notification settings - Fork 4.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix SendAsync from inpersonificated context with default credentials (…
…#58922) * fix SendAsync from inpersonificated context and default credentials * add missing file * remove dead code * feedback from review * name cleanup
- Loading branch information
Showing
9 changed files
with
508 additions
and
134 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
141 changes: 141 additions & 0 deletions
141
src/libraries/Common/tests/TestUtilities/System/WindowsIdentityFixture.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
94 changes: 94 additions & 0 deletions
94
src/libraries/System.Net.Http/tests/FunctionalTests/ImpersonatedAuthTests.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ImpersonatedAuthTests: IClassFixture<WindowsIdentityFixture> | ||
{ | ||
public static bool CanRunImpersonatedTests = PlatformDetection.IsWindows && PlatformDetection.IsNotWindowsNanoServer; | ||
private readonly WindowsIdentityFixture _fixture; | ||
private readonly ITestOutputHelper _output; | ||
|
||
public ImpersonatedAuthTests(WindowsIdentityFixture windowsIdentityFixture, ITestOutputHelper output) | ||
{ | ||
_output = output; | ||
_fixture = windowsIdentityFixture; | ||
|
||
Assert.False(_fixture.TestAccount.AccountTokenHandle.IsInvalid); | ||
Assert.False(string.IsNullOrEmpty(_fixture.TestAccount.AccountName)); | ||
} | ||
|
||
[OuterLoop] | ||
[ConditionalTheory(nameof(CanRunImpersonatedTests))] | ||
[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); | ||
}); | ||
|
||
} | ||
} | ||
} |
Oops, something went wrong.