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 3 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 @@ -96,8 +96,6 @@ public HttpConnectionSettings CloneAndNormalize()
_connectTimeout = _connectTimeout,
_credentials = _credentials,
_defaultProxyCredentials = _defaultProxyCredentials,
_defaultCredentialsUsedForProxy = _defaultCredentialsUsedForProxy,
_defaultCredentialsUsedForServer = _defaultCredentialsUsedForServer,
_expect100ContinueTimeout = _expect100ContinueTimeout,
_maxAutomaticRedirections = _maxAutomaticRedirections,
_maxConnectionsPerServer = _maxConnectionsPerServer,
Expand All @@ -123,6 +121,8 @@ public HttpConnectionSettings CloneAndNormalize()
_plaintextStreamFilter = _plaintextStreamFilter,
_initialHttp2StreamWindowSize = _initialHttp2StreamWindowSize,
_activityHeadersPropagator = _activityHeadersPropagator,
_defaultCredentialsUsedForProxy = _proxy != null && (_proxy.Credentials == CredentialCache.DefaultCredentials || _defaultProxyCredentials == CredentialCache.DefaultCredentials),
_defaultCredentialsUsedForServer = _credentials == CredentialCache.DefaultCredentials,
};

// TODO: Remove if/when QuicImplementationProvider is removed from System.Net.Quic.
Expand Down
Loading