public void Init() { var userToken = Properties["user1.token"]; var config = new Configuration(timeout: 10000, accessToken: userToken); instance = new TokensApi(config); }
/// <summary> /// Use this only to restrict a non-elevated token. /// This method is useless if you are already elevated because it can't /// remove you from Admin's group. (You are still administrator able to write in C:\windows). /// </summary> /// <param name="newToken"></param> public TokenProvider RestrictTokenMaxPrivilege(bool ignoreErrors = false) { uint DISABLE_MAX_PRIVILEGE = 0x1; uint LUA_TOKEN = 0x4; SafeTokenHandle result; if (!TokensApi.CreateRestrictedToken( Token, LUA_TOKEN | DISABLE_MAX_PRIVILEGE, //WRITE_RESTRICTED, 0, IntPtr.Zero, //pSA, 0, IntPtr.Zero, 0, IntPtr.Zero, out result) && !ignoreErrors) { throw new Win32Exception(); } Token.Close(); Token = result; return(this); }
public static TokenProvider CreateFromSaferApi(SaferLevels saferLevel) { IntPtr hSaferLevel; SafeTokenHandle hToken; if (!TokensApi.SaferCreateLevel(TokensApi.SaferScopes.User, saferLevel, 1, out hSaferLevel, IntPtr.Zero)) { throw new Win32Exception(); } try { if (!TokensApi.SaferComputeTokenFromLevel(hSaferLevel, IntPtr.Zero, out hToken, TokensApi.SaferComputeTokenFlags.None, IntPtr.Zero)) { throw new Win32Exception(); } } finally { SaferCloseLevel(hSaferLevel); } return(new TokenProvider() { Token = hToken }); }
private static SafeProcessHandle CreateProcessAsUser(SafeTokenHandle newToken, string appToRun, string args, string startupFolder, bool newWindow, bool hidden) { var si = new STARTUPINFO(); if (newWindow) { si.dwFlags = 0x00000001; // STARTF_USESHOWWINDOW si.wShowWindow = (short)(hidden ? 0 : 1); } si.cb = Marshal.SizeOf(si); var pi = new PROCESS_INFORMATION(); uint dwCreationFlags = newWindow ? (uint)CreateProcessFlags.CREATE_NEW_CONSOLE : 0; if (!TokensApi.CreateProcessAsUser(newToken, ArgumentsHelper.UnQuote(appToRun), $"{appToRun} {args}", IntPtr.Zero, IntPtr.Zero, false, dwCreationFlags, IntPtr.Zero, startupFolder, ref si, out pi)) { throw new Win32Exception(); } CloseHandle(pi.hThread); return(new SafeProcessHandle(pi.hProcess, true)); }
public void Initialize() { ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; _tokensApi = new TokensApi(TestApiSettings.Uri); _transactionsApi = new TransactionsApi(TestApiSettings.Uri); _tokensApi.Configuration.AddDefaultHeader("Authorization", "Api-Key " + TestApiSettings.PublicKey); _transactionsApi.Configuration.AddDefaultHeader("Authorization", "Api-Key " + TestApiSettings.PublicKey); }
public Boolean Disconnect() { if (loggedIn) { var tokensApi = new TokensApi(); tokensApi.DeleteTokensMe(); loggedIn = false; } return(false); }
public TokenProvider Duplicate(uint desiredAccess = 0x02000000) { if (!TokensApi.DuplicateTokenEx(Token.DangerousGetHandle(), desiredAccess, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out var newToken)) { throw new Win32Exception(); } Token.Close(); Token = newToken; return(this); }
public void Initialize() { ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; _transactionsApi = new TransactionsApi(TestApiSettings.Uri); _tokensApi = new TokensApi(TestApiSettings.Uri); var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(TestApiSettings.Key + ":" + TestApiSettings.Secret); _tokensApi.Configuration.AddDefaultHeader("Authorization", "Basic " + System.Convert.ToBase64String(plainTextBytes)); _transactionsApi.Configuration.AddDefaultHeader("Authorization", "Basic " + System.Convert.ToBase64String(plainTextBytes)); }
private void LogoutButton_Click(object sender, EventArgs e) { try { var api = new TokensApi(); api.DeleteTokensMe(); MessageBox.Show("DeleteTokensMe Request already sent, please check by hit Get User Button"); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public static Process StartWithProcessToken(int pidWithToken, string appToRun, string args, string startupFolder, bool hidden) { IntPtr existingProcessHandle = OpenProcess(PROCESS_QUERY_INFORMATION, true, (uint)pidWithToken); if (existingProcessHandle == IntPtr.Zero) { return(null); } IntPtr existingProcessToken, newToken; try { if (!OpenProcessToken(existingProcessHandle, TOKEN_DUPLICATE, out existingProcessToken)) { return(null); } } finally { CloseHandle(existingProcessHandle); } if (existingProcessToken == IntPtr.Zero) { return(null); } var sa = new SECURITY_ATTRIBUTES(); const uint MAXIMUM_ALLOWED = 0x02000000; if (!TokensApi.DuplicateTokenEx(existingProcessToken, MAXIMUM_ALLOWED, ref sa, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out newToken)) { return(null); } var STARTF_USESHOWWINDOW = 0x00000001; var startupInfo = new STARTUPINFO() { cb = (int)Marshal.SizeOf(typeof(STARTUPINFO)), dwFlags = STARTF_USESHOWWINDOW, wShowWindow = (short)(hidden ? 0 : 1), }; PROCESS_INFORMATION processInformation; if (!CreateProcessWithTokenW(newToken, 0, appToRun, $"{appToRun} {args}", 0, IntPtr.Zero, startupFolder, ref startupInfo, out processInformation)) { return(null); } return(Process.GetProcessById(processInformation.dwProcessId)); }
public TokenProvider GetLinkedToken(uint desiredAccess = MAXIMUM_ALLOWED) { // Now we allocate a buffer for the integrity level information. int cb = Marshal.SizeOf <TOKEN_LINKED_TOKEN>(); var pLinkedToken = Marshal.AllocHGlobal(cb); if (pLinkedToken == IntPtr.Zero) { throw new Win32Exception(); } try { // Now we ask for the integrity level information again. This may fail // if an administrator has added this account to an additional group // between our first call to GetTokenInformation and this one. if (!TokensApi.GetTokenInformation(Token.DangerousGetHandle(), TokensApi.TOKEN_INFORMATION_CLASS.TokenLinkedToken, pLinkedToken, cb, out cb)) { throw new Win32Exception(); } // Marshal the TOKEN_MANDATORY_LABEL struct from native to .NET object. TOKEN_LINKED_TOKEN linkedTokenStruct = (TOKEN_LINKED_TOKEN) Marshal.PtrToStructure(pLinkedToken, typeof(TOKEN_LINKED_TOKEN)); var sa = new SECURITY_ATTRIBUTES(); sa.nLength = 0; SafeTokenHandle newToken; if (!TokensApi.DuplicateTokenEx(linkedTokenStruct.LinkedToken, desiredAccess, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out newToken)) { throw new Win32Exception(); } CloseHandle(linkedTokenStruct.LinkedToken); this.Token.Close(); this.Token = newToken; } finally { Marshal.FreeHGlobal(pLinkedToken); } return(this); }
public void Should_Create_Get_And_Delete_With_Impersonation() { // setup var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(TestApiSettings.Key + ":" + TestApiSettings.Secret); var autoPayApi = new AutoPayApi(TestApiSettings.Uri); var tokensApi = new TokensApi(TestApiSettings.Uri); var postTokenRequestModel = new PostTokenRequestModel { Payer = "John Doe", EmailAddress = "*****@*****.**", CreditCardInformation = new CreditCardInformationModel { AccountHolder = "John Doe", CardNumber = "4457119922390123", Cvc = "123", Month = 12, Year = DateTime.Now.Year + 1, PostalCode = "54321" } }; autoPayApi.Configuration.AddDefaultHeader("Authorization", "Basic " + System.Convert.ToBase64String(plainTextBytes)); tokensApi.Configuration.AddDefaultHeader("Authorization", "Basic " + System.Convert.ToBase64String(plainTextBytes)); //Create Token var tokenId = tokensApi.TokensPost(postTokenRequestModel, TestApiSettings.InvoicesImpersonationAccountKey); var id = Guid.NewGuid(); var autopayRequestModel = new PostAutoPayRequestModel { EmailAddress = "*****@*****.**", AttributeValues = new Dictionary <string, string>() { ["accountCode"] = "123", ["postalCode"] = "78701", ["uniqueId"] = id.ToString() }, PublicTokenId = tokenId }; // Create and get autopay var createdId = autoPayApi.AutoPayPost(autopayRequestModel, TestApiSettings.InvoicesImpersonationAccountKey); var gotten = autoPayApi.AutoPayGet(createdId.Value, TestApiSettings.InvoicesImpersonationAccountKey); autoPayApi.AutoPayCancel(createdId.Value, TestApiSettings.InvoicesImpersonationAccountKey); Assert.IsNotNull(gotten); Assert.AreEqual(tokenId, gotten.TokenId); }
private void btnConnect_Click(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(txtClientId.Text) || string.IsNullOrEmpty(txtClientSecret.Text)) { MessageBox.Show("Enter a client id & secret first."); return; } // Connect to PureCloud AddLog("Connecting..."); Configuration.Default.ApiClient.RestClient.BaseUrl = new Uri($"https://api.{cmbEnvironment.SelectedItem.ToString()}"); var accessTokenInfo = Configuration.Default.ApiClient.PostToken(txtClientId.Text, txtClientSecret.Text); Configuration.Default.AccessToken = accessTokenInfo.AccessToken; loggedIn = true; AddLog("Connected!"); AddLog($"Access Token: {accessTokenInfo.AccessToken}", true); // Get APIs AddLog("Initializing APIs...", true); tokensApi = new TokensApi(); routingApi = new RoutingApi(); analyticsApi = new AnalyticsApi(); conversationsApi = new ConversationsApi(); AddLog("Finished initializing APIs...", true); // Update Controls btnConnect.Enabled = false; btnDisconnect.Enabled = true; gbQueues.Enabled = true; // Populate Queues GetQueues(); } catch (Exception ex) { AddLog($"Error in btnConnect_Click: {ex.Message}"); AddLog($"Detailled error: {ex}", true); MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); btnConnect.Enabled = true; btnDisconnect.Enabled = false; gbQueues.Enabled = false; loggedIn = false; } }
public void Should_Create_And_Delete() { // Setup var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(TestApiSettings.InvoiceKey + ":" + TestApiSettings.InvoiceSecret); var autoPayApi = new AutoPayApi(TestApiSettings.Uri); var tokensApi = new TokensApi(TestApiSettings.Uri); var postTokenRequestModel = new PostTokenRequestModel { Payer = "John Doe", EmailAddress = "*****@*****.**", CreditCardInformation = new CreditCardInformationModel { AccountHolder = "John Doe", CardNumber = "4457119922390123", Cvc = "123", Month = 12, Year = DateTime.Now.Year + 1, PostalCode = "54321" } }; autoPayApi.Configuration.AddDefaultHeader("Authorization", "Basic " + System.Convert.ToBase64String(plainTextBytes)); tokensApi.Configuration.AddDefaultHeader("Authorization", "Basic " + System.Convert.ToBase64String(plainTextBytes)); // Create Token var tokenId = tokensApi.TokensPost(postTokenRequestModel); var autopayRequestModel = new PostAutoPayRequestModel { EmailAddress = "*****@*****.**", AttributeValues = new Dictionary <string, string>() { ["accountCode"] = "123", ["postalCode"] = "78702" }, PublicTokenId = tokenId }; var createdId = autoPayApi.AutoPayPost(autopayRequestModel); var result = autoPayApi.AutoPayCancel(createdId.Value); Assert.IsTrue(result); }
/// <summary> /// Use this only to restrict a non-elevated token. /// This method is useless if you are already elevated because it can't /// remove you from Admin's group. (You are still administrator able to write in C:\windows). /// </summary> /// <param name="newToken"></param> public TokenProvider RestrictTokenMaxPrivilege(bool ignoreErrors = false) { // System.Security.Principal.WellKnownSidType.WorldSid; uint DISABLE_MAX_PRIVILEGE = 0x1; uint LUA_TOKEN = 0x4; uint WRITE_RESTRICTED = 0x8; SafeTokenHandle result; /* * string adminSid = "S-1-5-32-544"; * IntPtr pAdminSid; * if (!ConvertStringSidToSid(adminSid, out pAdminSid)) * throw new Win32Exception(); * * SID_AND_ATTRIBUTES sa = new SID_AND_ATTRIBUTES(); * sa.Sid = pAdminSid; * sa.Attributes = 0; * * var pSA = Marshal.AllocHGlobal(Marshal.SizeOf<SID_AND_ATTRIBUTES>()); * Marshal.StructureToPtr(sa, pSA, false); */ if (!TokensApi.CreateRestrictedToken( Token, LUA_TOKEN | DISABLE_MAX_PRIVILEGE, //WRITE_RESTRICTED, 0, IntPtr.Zero, //pSA, 0, IntPtr.Zero, 0, IntPtr.Zero, out result) && !ignoreErrors) { throw new Win32Exception(); } Token.Close(); Token = result; return(this); }
public static void ReplaceProcessToken(ElevationRequest elevationRequest) { SafeTokenHandle desiredToken; desiredToken = GetDesiredToken(elevationRequest); try { var tokenInfo = new TokensApi.PROCESS_ACCESS_TOKEN(); tokenInfo.Token = desiredToken.DangerousGetHandle(); tokenInfo.Thread = IntPtr.Zero; TokenProvider .CreateFromSystemAccount() .EnablePrivilege(Privilege.SeAssignPrimaryTokenPrivilege, true) .Impersonate(() => { IntPtr hProcess = ProcessApi.OpenProcess(ProcessApi.PROCESS_SET_INFORMATION, true, (uint)elevationRequest.TargetProcessId); TokensApi._PROCESS_INFORMATION_CLASS processInformationClass = TokensApi._PROCESS_INFORMATION_CLASS.ProcessAccessToken; int res = TokensApi.NtSetInformationProcess(hProcess, processInformationClass, ref tokenInfo, Marshal.SizeOf <TokensApi.PROCESS_ACCESS_TOKEN>()); Logger.Instance.Log($"NtSetInformationProcess returned {res}", LogLevel.Debug); if (res < 0) { throw new Win32Exception(); } ProcessApi.CloseHandle(hProcess); }); } finally { desiredToken?.Close(); } }
static internal int GetProcessIntegrityLevel(IntPtr processHandle) { /* * https://docs.microsoft.com/en-us/previous-versions/dotnet/articles/bb625963(v=msdn.10)?redirectedfrom=MSDN * https://support.microsoft.com/en-us/help/243330/well-known-security-identifiers-in-windows-operating-systems * S-1-16-0 Untrusted Mandatory Level An untrusted integrity level. * S-1-16-4096 Low Mandatory Level A low integrity level. * S-1-16-8192 Medium Mandatory Level A medium integrity level. * S-1-16-8448 Medium Plus Mandatory Level A medium plus integrity level. * S-1-16-12288 High Mandatory Level A high integrity level. * S-1-16-16384 System Mandatory Level A system integrity level. * S-1-16-20480 Protected Process Mandatory Level A protected-process integrity level. * S-1-16-28672 Secure Process Mandatory Level A secure process integrity level. */ int IL = -1; //SafeWaitHandle hToken = null; IntPtr hToken = IntPtr.Zero; int cbTokenIL = 0; IntPtr pTokenIL = IntPtr.Zero; try { // Open the access token of the current process with TOKEN_QUERY. if (!OpenProcessToken(processHandle, Native.TokensApi.TOKEN_QUERY, out hToken)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // Then we must query the size of the integrity level information // associated with the token. Note that we expect GetTokenInformation // to return false with the ERROR_INSUFFICIENT_BUFFER error code // because we've given it a null buffer. On exit cbTokenIL will tell // the size of the group information. if (!Native.TokensApi.GetTokenInformation(hToken, Native.TokensApi.TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, IntPtr.Zero, 0, out cbTokenIL)) { int error = Marshal.GetLastWin32Error(); const int ERROR_INSUFFICIENT_BUFFER = 0x7a; if (error != ERROR_INSUFFICIENT_BUFFER) { // When the process is run on operating systems prior to // Windows Vista, GetTokenInformation returns false with the // ERROR_INVALID_PARAMETER error code because // TokenIntegrityLevel is not supported on those OS's. throw new Win32Exception(error); } } // Now we allocate a buffer for the integrity level information. pTokenIL = Marshal.AllocHGlobal(cbTokenIL); if (pTokenIL == IntPtr.Zero) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // Now we ask for the integrity level information again. This may fail // if an administrator has added this account to an additional group // between our first call to GetTokenInformation and this one. if (!TokensApi.GetTokenInformation(hToken, TokensApi.TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, pTokenIL, cbTokenIL, out cbTokenIL)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // Marshal the TOKEN_MANDATORY_LABEL struct from native to .NET object. TokensApi.TOKEN_MANDATORY_LABEL tokenIL = (TokensApi.TOKEN_MANDATORY_LABEL) Marshal.PtrToStructure(pTokenIL, typeof(TokensApi.TOKEN_MANDATORY_LABEL)); IntPtr pIL = TokensApi.GetSidSubAuthority(tokenIL.Label.Sid, 0); IL = Marshal.ReadInt32(pIL); } finally { // Centralized cleanup for all allocated resources. Clean up only // those which were allocated, and clean them up in the right order. if (hToken != IntPtr.Zero) { CloseHandle(hToken); // Marshal.FreeHGlobal(hToken); // hToken.Close(); // hToken = null; } if (pTokenIL != IntPtr.Zero) { Marshal.FreeHGlobal(pTokenIL); pTokenIL = IntPtr.Zero; cbTokenIL = 0; } } return((_cacheGetCurrentIntegrityLevelCache = IL).Value); }
private void btnConnect_Click(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(txtClientId.Text) || string.IsNullOrEmpty(txtClientSecret.Text)) { MessageBox.Show("Enter a client id & secret first."); return; } // Connect to PureCloud AddLog("Connecting..."); Configuration.Default.ApiClient.RestClient.BaseUrl = new Uri($"https://api.{cmbEnvironment.SelectedItem.ToString()}"); var accessTokenInfo = Configuration.Default.ApiClient.PostToken(txtClientId.Text, txtClientSecret.Text); Configuration.Default.AccessToken = accessTokenInfo.AccessToken; loggedIn = true; AddLog($"Connected."); AddLog($"Access Token: {accessTokenInfo.AccessToken}", true); // Get APIs AddLog("Initializing APIs...", true); analyticsApi = new AnalyticsApi(); routingApi = new RoutingApi(); conversationsApi = new ConversationsApi(); tokensApi = new TokensApi(); telephonyProvidersEdgeApi = new TelephonyProvidersEdgeApi(); AddLog("Finished initializing APIs...", true); // Update Controls btnConnect.Enabled = false; btnDisconnect.Enabled = true; gbEdges.Enabled = true; gbTroubleshooting.Enabled = true; gbAgents.Enabled = true; gbTestGhostCall.Enabled = true; gbCounters.Enabled = true; // Populate Edges GetEdges(); // Get Agents Stats AddLog("Starting timer for monitoring agent status", true); PullAgentsData(); timer.Interval = 5000; timer.Tick += (object timerSender, EventArgs eventArgs) => { PullAgentsData(); }; timer.Start(); AddLog("Timer started", true); } catch (Exception ex) { AddLog($"Error in btnConnect_Click: {ex.Message}"); AddLog($"Detailled error: {ex}", true); MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); btnConnect.Enabled = true; btnDisconnect.Enabled = false; gbEdges.Enabled = false; gbTroubleshooting.Enabled = false; gbAgents.Enabled = false; gbTestGhostCall.Enabled = false; gbCounters.Enabled = false; loggedIn = false; } }
public static TokenProvider CreateFromProcessToken(int pidWithToken, uint tokenAccess = MAXIMUM_ALLOWED) { IntPtr existingProcessHandle = OpenProcess(PROCESS_QUERY_INFORMATION, true, (uint)pidWithToken); if (existingProcessHandle == IntPtr.Zero) { throw new Win32Exception(); } IntPtr existingProcessToken; try { if (!ProcessApi.OpenProcessToken(existingProcessHandle, MAXIMUM_ALLOWED //| TOKEN_ALL_ACCESS, //| TOKEN_DUPLICATE //| TokensApi.TOKEN_ADJUST_DEFAULT | //| TokensApi.TOKEN_QUERY //| TokensApi.TOKEN_ASSIGN_PRIMARY //| TOKEN_QUERY_SOURCE //| TOKEN_IMPERSONATE //| TOKEN_READ //| TOKEN_ALL_ACCESS ==> access denied //| STANDARD_RIGHTS_REQUIRED ==> access denied. , out existingProcessToken)) { throw new Win32Exception(); } } finally { CloseHandle(existingProcessHandle); } if (existingProcessToken == IntPtr.Zero) { return(null); } var sa = new SECURITY_ATTRIBUTES(); sa.nLength = 0; uint desiredAccess = MAXIMUM_ALLOWED; SafeTokenHandle newToken; if (!TokensApi.DuplicateTokenEx(existingProcessToken, desiredAccess, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out newToken)) { CloseHandle(existingProcessToken); throw new Win32Exception(); } CloseHandle(existingProcessToken); return(new TokenProvider() { Token = newToken }); }
public void Cleanup() { instance = null; }
public void Init() { instance = new TokensApi(); }