public async Task <HashSet <string> > GetDistinctValidReportScenariosAsync(SafeAccessTokenHandle accessToken) { return(await GetDistinctValidReportParamValues <string>(accessToken, "[dbo].[DimScenario]", "[ScenarioCode]")); }
public async Task <HashSet <string> > GetDistinctValidActualToPmScenariosAsync(SafeAccessTokenHandle accessToken) { return(await GetDistinctValues <string>(accessToken, "[dbo].[DimScenario]", "[ScenarioCode]", "[ScenarioID] NOT IN (1,2)")); }
internal static extern bool OpenProcessToken( #endif IntPtr ProcessToken, TokenAccessLevels DesiredAccess, out SafeAccessTokenHandle TokenHandle);
public async Task <HashSet <string> > GetDistinctValidReportEntitiesAsync(SafeAccessTokenHandle accessToken) { return(await GetDistinctValidReportParamValues <string>(accessToken, "[dbo].[DimEntity]", "[EntityDesc]")); }
internal static extern bool GetTokenInformation(SafeAccessTokenHandle hToken, TOKEN_INFORMATION_CLASS tokenInfoClass, IntPtr tokenInformation, int tokeInfoLength, ref int reqLength);
internal static extern bool GetTokenInformation( SafeAccessTokenHandle TokenHandle, uint TokenInformationClass, SafeLocalAllocHandle TokenInformation, uint TokenInformationLength, out uint ReturnLength);
internal static extern unsafe bool GetTokenInformation( SafeAccessTokenHandle TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, void *TokenInformation, uint TokenInformationLength, out uint ReturnLength);
private static partial bool LogonUser(string userName, string domain, string password, int logonType, int logonProvider, out SafeAccessTokenHandle safeAccessTokenHandle);
/// <summary> /// Initializes a new instance of the WindowsIdentity class for the user represented by the specified User Principal Name (UPN). /// </summary> /// <remarks> /// Unlike the desktop version, we connect to Lsa only as an untrusted caller. We do not attempt to explot Tcb privilege or adjust the current /// thread privilege to include Tcb. /// </remarks> public WindowsIdentity(string sUserPrincipalName) : base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid) { // Desktop compat: See comments below for why we don't validate sUserPrincipalName. using (SafeLsaHandle lsaHandle = ConnectToLsa()) { int packageId = LookupAuthenticationPackage(lsaHandle, Interop.SspiCli.AuthenticationPackageNames.MICROSOFT_KERBEROS_NAME_A); // 8 byte or less name that indicates the source of the access token. This choice of name is visible to callers through the native GetTokenInformation() api // so we'll use the same name the CLR used even though we're not actually the "CLR." byte[] sourceName = { (byte)'C', (byte)'L', (byte)'R', (byte)0 }; TOKEN_SOURCE sourceContext; if (!Interop.Advapi32.AllocateLocallyUniqueId(out sourceContext.SourceIdentifier)) { throw new SecurityException(new Win32Exception().Message); } sourceContext.SourceName = new byte[TOKEN_SOURCE.TOKEN_SOURCE_LENGTH]; Buffer.BlockCopy(sourceName, 0, sourceContext.SourceName, 0, sourceName.Length); // Desktop compat: Desktop never null-checks sUserPrincipalName. Actual behavior is that the null makes it down to Encoding.Unicode.GetBytes() which then throws // the ArgumentNullException (provided that the prior LSA calls didn't fail first.) To make this compat decision explicit, we'll null check ourselves // and simulate the exception from Encoding.Unicode.GetBytes(). if (sUserPrincipalName == null) { throw new ArgumentNullException("s"); } byte[] upnBytes = Encoding.Unicode.GetBytes(sUserPrincipalName); if (upnBytes.Length > ushort.MaxValue) { // Desktop compat: LSA only allocates 16 bits to hold the UPN size. We should throw an exception here but unfortunately, the desktop did an unchecked cast to ushort, // effectively truncating upnBytes to the first (N % 64K) bytes. We'll simulate the same behavior here (albeit in a way that makes it look less accidental.) Array.Resize(ref upnBytes, upnBytes.Length & ushort.MaxValue); } unsafe { // // Build the KERB_S4U_LOGON structure. Note that the LSA expects this entire // structure to be contained within the same block of memory, so we need to allocate // enough room for both the structure itself and the UPN string in a single buffer // and do the marshalling into this buffer by hand. // int authenticationInfoLength = checked (sizeof(KERB_S4U_LOGON) + upnBytes.Length); using (SafeLocalAllocHandle authenticationInfo = Interop.Kernel32.LocalAlloc(0, new UIntPtr(checked ((uint)authenticationInfoLength)))) { if (authenticationInfo.IsInvalid) { throw new OutOfMemoryException(); } KERB_S4U_LOGON *pKerbS4uLogin = (KERB_S4U_LOGON *)(authenticationInfo.DangerousGetHandle()); pKerbS4uLogin->MessageType = KERB_LOGON_SUBMIT_TYPE.KerbS4ULogon; pKerbS4uLogin->Flags = KerbS4uLogonFlags.None; pKerbS4uLogin->ClientUpn.Length = pKerbS4uLogin->ClientUpn.MaximumLength = checked ((ushort)upnBytes.Length); IntPtr pUpnOffset = (IntPtr)(pKerbS4uLogin + 1); pKerbS4uLogin->ClientUpn.Buffer = pUpnOffset; Marshal.Copy(upnBytes, 0, pKerbS4uLogin->ClientUpn.Buffer, upnBytes.Length); pKerbS4uLogin->ClientRealm.Length = pKerbS4uLogin->ClientRealm.MaximumLength = 0; pKerbS4uLogin->ClientRealm.Buffer = IntPtr.Zero; ushort sourceNameLength = checked ((ushort)(sourceName.Length)); using (SafeLocalAllocHandle sourceNameBuffer = Interop.Kernel32.LocalAlloc(0, new UIntPtr(sourceNameLength))) { if (sourceNameBuffer.IsInvalid) { throw new OutOfMemoryException(); } Marshal.Copy(sourceName, 0, sourceNameBuffer.DangerousGetHandle(), sourceName.Length); LSA_STRING lsaOriginName = new LSA_STRING(sourceNameBuffer.DangerousGetHandle(), sourceNameLength); SafeLsaReturnBufferHandle profileBuffer; int profileBufferLength; LUID logonId; SafeAccessTokenHandle accessTokenHandle; QUOTA_LIMITS quota; int subStatus; int ntStatus = Interop.SspiCli.LsaLogonUser( lsaHandle, ref lsaOriginName, SECURITY_LOGON_TYPE.Network, packageId, authenticationInfo.DangerousGetHandle(), authenticationInfoLength, IntPtr.Zero, ref sourceContext, out profileBuffer, out profileBufferLength, out logonId, out accessTokenHandle, out quota, out subStatus); if (ntStatus == unchecked ((int)Interop.StatusOptions.STATUS_ACCOUNT_RESTRICTION) && subStatus < 0) { ntStatus = subStatus; } if (ntStatus < 0) // non-negative numbers indicate success { throw GetExceptionFromNtStatus(ntStatus); } if (subStatus < 0) // non-negative numbers indicate success { throw GetExceptionFromNtStatus(subStatus); } if (profileBuffer != null) { profileBuffer.Dispose(); } _safeTokenHandle = accessTokenHandle; } } } } }
internal static extern bool AuthzInitializeContextFromToken(AuthzInitFlags flags, SafeAccessTokenHandle hToken, SafeAuthzResourceManagerHandle authRm, IntPtr expirationTime, Luid identifier, IntPtr dynamicGroupArgs, out SafeAuthzContextHandle authzClientContext);
internal static partial bool ImpersonateLoggedOnUser(SafeAccessTokenHandle userToken);
internal static bool OpenThreadToken(TokenAccessLevels desiredAccess, WinSecurityContext openAs, out SafeAccessTokenHandle tokenHandle) { bool openAsSelf = true; if (openAs == WinSecurityContext.Thread) { openAsSelf = false; } if (OpenThreadToken(Kernel32.GetCurrentThread(), desiredAccess, openAsSelf, out tokenHandle)) { return(true); } if (openAs == WinSecurityContext.Both) { openAsSelf = false; tokenHandle.Dispose(); if (OpenThreadToken(Kernel32.GetCurrentThread(), desiredAccess, openAsSelf, out tokenHandle)) { return(true); } } return(false); }
private static partial bool OpenThreadToken( IntPtr ThreadHandle, TokenAccessLevels dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bOpenAsSelf, out SafeAccessTokenHandle phThreadToken);
public async Task <HashSet <string> > GetDistinctValidActualToPmYearsAsync(SafeAccessTokenHandle accessToken) { return(await GetDistinctValues <string>(accessToken, "[dbo].[DimYear]", "[YearCode]")); }
public static void RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action) { throw new NotImplementedException(); }
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeAccessTokenHandle phToken);
public static T RunImpersonated <T> (SafeAccessTokenHandle safeAccessTokenHandle, Func <T> func) { throw new NotImplementedException(); }
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); } } else 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(); } } } }
internal static extern bool OpenProcessToken(SafeProcessHandle processHandle, int desiredAccess, out SafeAccessTokenHandle tokenHandle);