protected virtual bool IsAdmin() { bool isAdmin = false; try { var identity = WindowsIdentity.GetCurrent(); var principal = new WindowsPrincipal(identity); isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator) // The system account, while an admin, cannot start processes as another user. // // From MSDN: // You cannot call CreateProcessWithLogonW from a process that is running under // the "LocalSystem" account, because the function uses the logon SID in the // caller token, and the token for the "LocalSystem" account does not contain // this SID // // Thus, if running as System, skip. && !identity.IsSystem; } catch { isAdmin = false; } return isAdmin; }
/// <summary> /// Get the security level of the user account. /// </summary> /// <param name="currentPrincipal"></param> /// <returns></returns> public static SecurityLevel GetSecurityLevel() { try { if ((ConfigurationManager.AppSettings.Keys.Count > 0) && (!string.IsNullOrEmpty(AppSettings.AuthorGroupName))) { //Check if the principal for the request is member of the admin group var principal = new WindowsPrincipal(securityContext.WindowsIdentity); if (!principal.IsInRole(AppSettings.AuthorGroupName)) { string message = string.Format( AuthMessages.InvalidCredentials, securityContext.WindowsIdentity.Name, AppSettings.AuthorGroupName); var ex = new UnauthorizedAccessException(message); Logging.Log(LoggingValues.InvalidCredentials, System.Diagnostics.EventLogEntryType.Error, null, ex); throw ex; } } } catch (AppDomainUnloadedException) { return SecurityLevel.Offline; } catch { return SecurityLevel.NoAccess; } }
static public int Main(string[] args) { try { string fileExtension = GetArg("-e:"); string programId = GetArg("-prog:"); string hash = GetArg("-hash:"); if (fileExtension == "" || programId == "" || hash == "") { Console.WriteLine(Usage); } else { bool isAdmin = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator) ? true : false; if (!isAdmin) throw new Exception("Error: You need to run this application as administrator."); ChooseDefaultProgram.Set(fileExtension, programId, hash); } } catch (Exception e) { Console.WriteLine("Error: " + e.Message); return 1; } return 0; }
public static void WindowsPrincipalIsInRoleNeg() { WindowsIdentity windowsIdentity = WindowsIdentity.GetAnonymous(); WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity); var ret = windowsPrincipal.IsInRole("FAKEDOMAIN\\nonexist"); Assert.False(ret); }
public static bool IsAdministrator() { using (var windowsIdentity = WindowsIdentity.GetCurrent()) { var windowsPrincipal = new WindowsPrincipal(windowsIdentity); return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator); } }
public static void ByPass() { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); if (principal.IsInRole(WindowsBuiltInRole.Administrator) == false) { ProcessStartInfo processInfo = new ProcessStartInfo(); processInfo.FileName = "cmd.exe"; processInfo.Arguments = "/c start \"\" \"" + Application.ExecutablePath + "\""; processInfo.Verb = "runas"; processInfo.WindowStyle = ProcessWindowStyle.Hidden; try { Process.Start(processInfo); } catch (Exception) { //Probably the user canceled the UAC window MessageBox.Show("获取管理员权限失败!你可能无法控制某些窗口的鼠标键盘操作。", "提示"); return; } Environment.Exit(0); } }
private static bool IsAnAdministrator() { WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); return(principal.IsInRole(WindowsBuiltInRole.Administrator)); }
public CurrentUserSecurity() { _currentUser = WindowsIdentity.GetCurrent(); _currentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); }
static void Main(string[] args) { //Do some UAC checks WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator); if (!hasAdministrativeRight) { RunElevated(Process.GetCurrentProcess().MainModule.FileName); return; } // This opens the phonebook so it can be used. Different overloads here will determine where the phonebook is opened/created. AllUsersPhoneBook.Open(); string EntryName = System.Configuration.ConfigurationManager.AppSettings["DialupName"]; if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["host"])) { // Create the entry that will be used by the dialer to dial the connection. Entries can be created manually, however the static methods on // the RasEntry class shown below contain default information matching that what is set by Windows for each platform. RasEntry entry = RasEntry.CreateVpnEntry(EntryName, System.Configuration.ConfigurationManager.AppSettings["host"], RasVpnStrategy.PptpFirst, RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn)); // Add the new entry to the phone book. try { AllUsersPhoneBook.Entries.Add(entry); } catch (System.ArgumentException err) { int x = 0; //Most likely, already exists. Continue on and try connection. } } Dialer.EntryName = EntryName; Dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.AllUsers); Dialer.StateChanged += new EventHandler <StateChangedEventArgs>(Dialer_StateChanged); Dialer.DialCompleted += new EventHandler <DialCompletedEventArgs>(Dialer_DialCompleted); try { if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["User"])) { Dialer.AllowUseStoredCredentials = true; } else { // Set the credentials the dialer should use. Dialer.Credentials = new NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["User"], System.Configuration.ConfigurationManager.AppSettings["pass"]); } // NOTE: The entry MUST be in the phone book before the connection can be dialed. Dialer.Dial(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); return; } foreach (string routeLine in System.Configuration.ConfigurationManager.AppSettings["route"].Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) { string[] parts = routeLine.Split(" ".ToCharArray()); AddRoute(parts[0], parts[1], parts[2]); } }
static int Main(string[] args) { int retCode = 1; // assume error // // Check if CurrentUICulture needs to be overridden // UDDI.Localization.SetConsoleUICulture(); Console.WriteLine(FormatFromResource("BOOTSTRAP_COPYRIGHT_1")); Console.WriteLine(FormatFromResource("BOOTSTRAP_COPYRIGHT_2")); Console.WriteLine(); // // parse the command line // if (!ProcessCommandLine(args)) { return(1); } WindowsPrincipal prin = new WindowsPrincipal(WindowsIdentity.GetCurrent()); try { ConnectionManager.Open(true, true); } catch { Console.WriteLine(FormatFromResource("BOOTSTRAP_DB_CONNECT_FAILED")); return(1); } try { // // Setup the UDDI user credentials // Context.User.SetRole(prin); // // Verify that the user is a member of the administrators group // if (!Context.User.IsAdministrator) { // // 735728 - Show an error to the user and exit the program. // Console.WriteLine(FormatFromResource("BOOTSTRAP_ACCESS_DENIED")); Console.WriteLine(FormatFromResource("BOOTSTRAP_ADMIN_GROUP_ONLY")); Console.WriteLine(FormatFromResource("BOOTSTRAP_USER_NOT_ADMIN", WindowsIdentity.GetCurrent().Name)); return(1); } if (null != username && 0 != username.Length) { // // The /u option was specified // Context.User.SetPublisherRole(username); if (!Context.User.IsRegistered) { // // 735728 - Show an error to the user and exit the program. // Console.WriteLine(FormatFromResource("BOOTSTRAP_USER_NOT_REGISTERED", username)); return(1); } // // If the current user is not the same as the publisher, set up impersonation // if (Context.User.ID != WindowsIdentity.GetCurrent().Name) { Context.User.ImpersonatorID = WindowsIdentity.GetCurrent().Name; } } else { // // Default is to save data under the default publisher // Context.User.ID = UDDI.Utility.GetDefaultPublisher(); } // // If user is not system publisher, a temporary operator must be added to support pre-assigned key behavior // string operatorkey = System.Guid.NewGuid().ToString(); if (Context.User.ID != UDDI.Utility.GetDefaultPublisher()) { Context.User.SetAllowPreassignedKeys(true); } XmlSerializer serializer = new XmlSerializer(typeof(UDDI.API.Extensions.Resources)); // // Load the XML file. // Console.WriteLine(FormatFromResource("BOOTSTRAP_PROCESSING_MSG", filename, Context.User.ID)); FileStream strm = new FileStream(filename, FileMode.Open, FileAccess.Read); Resources.Validate(strm); Resources resources = (Resources)serializer.Deserialize(strm); strm.Close(); // // Save the TModel // Console.WriteLine(FormatFromResource("BOOTSTRAP_SAVING")); // // Determine the number of tModels that we imported. // int tModelCount = 0; if (null != resources.TModelDetail) { tModelCount += resources.TModelDetail.TModels.Count; } if (null != resources.CategorizationSchemes) { foreach (CategorizationScheme scheme in resources.CategorizationSchemes) { if (null != scheme.TModel) { tModelCount++; } } } Console.WriteLine(FormatFromResource("BOOTSTRAP_TMODELS", tModelCount)); if (null != resources.CategorizationSchemes) { Console.WriteLine(FormatFromResource("BOOTSTRAP_CATEGORIZATION_SCHEMES", resources.CategorizationSchemes.Count)); } else { Console.WriteLine(FormatFromResource("BOOTSTRAP_CATEGORIZATION_SCHEMES", 0)); } if (null != resources.BusinessDetail) { Console.WriteLine(FormatFromResource("BOOTSTRAP_PROVIDERS", resources.BusinessDetail.BusinessEntities.Count)); } else { Console.WriteLine(FormatFromResource("BOOTSTRAP_PROVIDERS", 0)); } if (null != resources.ServiceDetail) { Console.WriteLine(FormatFromResource("BOOTSTRAP_SERVICES", resources.ServiceDetail.BusinessServices.Count)); } else { Console.WriteLine(FormatFromResource("BOOTSTRAP_SERVICES", 0)); } if (null != resources.BindingDetail) { Console.WriteLine(FormatFromResource("BOOTSTRAP_BINDINGS", resources.BindingDetail.BindingTemplates.Count)); } else { Console.WriteLine(FormatFromResource("BOOTSTRAP_BINDINGS", 0)); } resources.Save(); Console.WriteLine(FormatFromResource("BOOTSTRAP_COMPLETE")); ConnectionManager.Commit(); retCode = 0; // no error } catch (Exception e) { Console.WriteLine(); Console.WriteLine(FormatFromResource("BOOTSTRAP_FAILED", e.Message)); // // 735713 - Output an additional message if the user did not have permissions to modify an entity. // SqlException sqlException = e as SqlException; if (null != sqlException) { if (sqlException.Number - UDDI.Constants.ErrorTypeSQLOffset == ( int )ErrorType.E_userMismatch) { Console.WriteLine(FormatFromResource("ERROR_USER_MISMATCH")); } } ConnectionManager.Abort(); } finally { ConnectionManager.Close(); } return(retCode); }
/// <summary> /// Get the authentication principal for the specified identity /// </summary> /// <param name="identity">The identity to get the principal for</param> /// <returns>The principal for the user</returns> public static IPrincipal GetPrincipal(WindowsIdentity identity) { IPrincipal principal = new WindowsPrincipal(identity); return(principal); }
static void Main() { // Check whether the user is in Windows Admin mode #if !DEBUG WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); if (Environment.OSVersion.Platform == PlatformID.Win32NT && !principal.IsInRole(WindowsBuiltInRole.Administrator)) { string cmdLine = Environment.CommandLine.Substring(Environment.CommandLine.IndexOf(".exe") + 4); cmdLine = cmdLine.Contains(' ') ? cmdLine.Substring(cmdLine.IndexOf(" ")) : null; ProcessStartInfo psi = new ProcessStartInfo(Assembly.GetEntryAssembly().Location, cmdLine); psi.Verb = "runas"; Trace.TraceInformation("Not administrator!"); Process proc = Process.Start(psi); Application.Exit(); return; } #endif Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); AppDomain.CurrentDomain.SetData( "DataDirectory", Path.GetDirectoryName(typeof(Program).Assembly.Location)); ApplicationServiceContext.Current = ConfigurationContext.Current; AuthenticationContext.Current = new AuthenticationContext(AuthenticationContext.SystemPrincipal); // Current dir var cwd = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); // Load assembly var splash = new frmSplash(); splash.Show(); // Load assemblies var fileList = Directory.GetFiles(cwd, "*.dll"); int i = 0; foreach (var file in fileList) { try { splash.NotifyStatus($"Loading {Path.GetFileNameWithoutExtension(file)}...", ((float)(i++) / fileList.Length) * 0.5f); var asm = Assembly.LoadFile(file); // Now load all plugins on the assembly var pluginInfo = asm.GetCustomAttribute <PluginAttribute>(); if (pluginInfo != null) { ConfigurationContext.Current.PluginAssemblies.Add(asm); } } catch (Exception e) { Trace.TraceError("Unable to load {0}: {1}", file, e); } } // Load the current configuration try { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; splash.NotifyStatus("Loading Configuration....", 0.6f); if (!File.Exists(ConfigurationContext.Current.ConfigurationFile)) { splash.NotifyStatus("Preparing initial configuration...", 1f); // TODO: Launch initial configuration splash.Close(); ConfigurationContext.Current.InitialStart(); var init = new frmInitialConfig(); if (init.ShowDialog() == DialogResult.Cancel) { return; } } else if (!ConfigurationContext.Current.LoadConfiguration(ConfigurationContext.Current.ConfigurationFile)) { splash.Close(); return; } else { splash.NotifyStatus("Loading Configuration...", -1f); ConfigurationContext.Current.Start(); splash.Close(); } // Check for updates foreach (var t in ConfigurationContext.Current.Features .Where(o => o.Flags.HasFlag(FeatureFlags.AlwaysConfigure) && !o.Flags.HasFlag(FeatureFlags.SystemFeature)) .SelectMany(o => o.CreateInstallTasks()) .Where(o => o.VerifyState(ConfigurationContext.Current.Configuration))) { ConfigurationContext.Current.ConfigurationTasks.Add(t); } ConfigurationContext.Current.Apply(); Application.Run(new frmMain()); } finally { Environment.Exit(0); } }
[System.Security.SecuritySafeCritical] // auto-generated public void Demand() { IPrincipal principal = null; #if FEATURE_IMPERSONATION new SecurityPermission(SecurityPermissionFlag.ControlPrincipal).Assert(); principal = Thread.CurrentPrincipal; #endif // FEATURE_IMPERSONATION if (principal == null) { ThrowSecurityException(); } if (m_array == null) { return; } // A demand passes when the grant satisfies all entries. int count = this.m_array.Length; bool foundMatch = false; for (int i = 0; i < count; ++i) { // If the demand is authenticated, we need to check the identity and role if (m_array[i].m_authenticated) { IIdentity identity = principal.Identity; if ((identity.IsAuthenticated && (m_array[i].m_id == null || String.Compare(identity.Name, m_array[i].m_id, StringComparison.OrdinalIgnoreCase) == 0))) { if (m_array[i].m_role == null) { foundMatch = true; } else { #if !FEATURE_PAL && FEATURE_IMPERSONATION WindowsPrincipal wp = principal as WindowsPrincipal; if (wp != null && m_array[i].Sid != null) { foundMatch = wp.IsInRole(m_array[i].Sid); } else #endif // !FEATURE_PAL && FEATURE_IMPERSONATION foundMatch = principal.IsInRole(m_array[i].m_role); } if (foundMatch) { break; } } } else { foundMatch = true; break; } } if (!foundMatch) { ThrowSecurityException(); } }
/// <summary> /// The function checks whether the current process is run as administrator. /// In other words, it dictates whether the primary access token of the /// process belongs to user account that is a member of the local /// Administrators group and it is elevated. /// </summary> /// <returns> /// Returns true if the primary access token of the process belongs to user /// account that is a member of the local Administrators group and it is /// elevated. Returns false if the token does not. /// </returns> internal static bool IsRunAsAdmin() { WindowsIdentity id = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(id); return principal.IsInRole(WindowsBuiltInRole.Administrator); }
private bool GetAdminBool() { bool isAdmin; try { //get the currently logged in user WindowsIdentity user = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(user); isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); } catch (UnauthorizedAccessException) { isAdmin = false; } catch (Exception) { isAdmin = false; } return isAdmin; }
/// **************************************************************** /// protected OnInit /// ---------------------------------------------------------------- /// <summary> /// Initializes the security control. /// </summary> /// **************************************************************** /// protected override void OnInit(EventArgs e) { // // Check to make sure config settings are fresh. // Config.CheckForUpdate(); // // Check to see if the server has been manually stopped. // if (0 == Config.GetInt("Run", 1)) { #if never throw new UDDIException( ErrorType.E_busy, "UDDI Services are currently unavailable."); #endif throw new UDDIException(ErrorType.E_busy, "UDDI_ERROR_SERVICES_NOT_AVAILABLE"); } int mode = Config.GetInt("Security.AuthenticationMode", (int)AuthenticationMode.Windows); // // TODO: This code should be simplified to simple if statements. // It is obviously old code that needs to be updated. // if ((mode & (int)AuthenticationMode.Passport) != 0) { // // SECURITY: Passport.TimeWindow should be the same // timeout as API authentication. // passport = (PassportIdentity)Context.User.Identity; timeWindow = Config.GetInt("Passport.TimeWindow", 14400); string thisUrl = (Request.IsSecureConnection ? "https://" : "http://") + Request.ServerVariables["SERVER_NAME"] + Request.ServerVariables["SCRIPT_NAME"]; if (Utility.StringEmpty(ReturnUrl)) { ReturnUrl = thisUrl; } // // If the user just logged in, clean up the query string by redirecting // to this page. // if (passport.GetFromNetworkServer) { Response.Redirect(thisUrl); } // // Check to see if the current role is more that a passport user // can do. // if (AdminRequired || CoordinatorRequired) { // //Passport Users are not allowed in these areas. // #if never throw new UDDIException( ErrorType.E_unknownUser, "Access denied."); #endif throw new UDDIException( ErrorType.E_unknownUser, "UDDI_ERROR_ACCESS_DENIED"); } // // Check to see if the user is authenticated. // if (!passport.GetIsAuthenticated(timeWindow, ForceLogin, false)) { // // If the user already has a ticket, force them to re-enter // their password. // if (passport.HasTicket) { bool secure = Request.IsSecureConnection; // // Update this to AuthUrl2 when Passport .NET support is updated. // Response.Redirect(passport.AuthUrl(ReturnUrl, timeWindow, ForceLogin, "", 0, "", 0, secure)); } // // If login is required, redirect the user to the login page. // if (PublisherRequired) { Response.Redirect(LoginUrl + "?publish=true"); } } else { string userID = passport.HexPUID; // // Check to ensure that the passport UserID is not "" // if it is, force them to retype thier password // // if( ""==userID ) // Response.Redirect( LoginUrl ); string email = (string)passport.GetProfileObject("PreferredEmail"); UDDI.Context.User.SetPublisherRole(userID); if (PublisherRequired) { // // SECURITY: Is Validate the same as IsRegistered? // lucasm: no, Validate makes sure the registered publisher has validated // the email address they have supplied. IsRegistered checks to see // if we have added this uses to the publishers table. // int valid = Publisher.Validate(userID); if (50013 == valid) { // // Need to create a page that tells the // user to click the link in the email // Response.Redirect(LoginUrl); } else if (0 != valid) { Response.Redirect(LoginUrl); } Publisher publisher = new Publisher(); publisher.Login(userID, email); if (null == email) { email = publisher.Email; } // // TODO: this REALLY should be merged with the PublisherInfo class // in core!! // UDDI.Context.User.Name = publisher.Name; UDDI.Context.User.BindingLimit = publisher.BindingLimit; UDDI.Context.User.BusinessCount = publisher.BusinessCount; UDDI.Context.User.BusinessLimit = publisher.BusinessLimit; UDDI.Context.User.CompanyName = publisher.CompanyName; UDDI.Context.User.IsoLangCode = publisher.IsoLangCode; UDDI.Context.User.ServiceLimit = publisher.ServiceLimit; UDDI.Context.User.TModelCount = publisher.TModelCount; UDDI.Context.User.TModelLimit = publisher.TModelLimit; } // // Save the credentials for the authenticated user. // UDDI.Context.User.ID = userID; UDDI.Context.User.Email = email; } } else { WindowsPrincipal principal = (WindowsPrincipal)HttpContext.Current.User; UDDI.Context.User.SetRole(principal); UDDI.Context.User.Name = principal.Identity.Name; if (UserRequired && !UDDI.Context.User.IsUser && (mode & (int)AuthenticationMode.AuthenticatedRead) != 0 || PublisherRequired && !UDDI.Context.User.IsPublisher || CoordinatorRequired && !UDDI.Context.User.IsCoordinator || AdminRequired && !UDDI.Context.User.IsAdministrator) { #if never throw new UDDIException( ErrorType.E_unknownUser, "Access denied."); #endif throw new UDDIException(ErrorType.E_unknownUser, "UDDI_ERROR_ACCESS_DENIED"); } if (PublisherRequired || CoordinatorRequired || AdminRequired) { if (!UDDI.Context.User.IsRegistered) { if (1 == Config.GetInt("Security.AutoRegister", 0)) { UDDI.Context.User.TrackPassport = false; UDDI.Context.User.Verified = true; UDDI.Context.User.Register(); } else { #if never throw new UDDIException(UDDI.ErrorType.E_unknownUser, "User login failed"); #endif throw new UDDIException(UDDI.ErrorType.E_unknownUser, "UDDI_ERROR_USER_LOGIN_FAILED"); } } UDDI.Context.User.Login(); } } // // SECURITY: put this in the Windows Authentication block... not available // for Passport auth. // // If the user is a coordinator and they have a cookie indicating they are // impersonating another user, setup the user info in the current UDDI // context. // // // 734292 - Make sure the user is an administrator if they are trying to impersonate the system. // if (true == ViewAsPublisher.IsValid()) { UDDI.Context.User.ImpersonatorID = UDDI.Context.User.ID; UDDI.Context.User.ID = ViewAsPublisher.GetPublisherID(); } }
internal const int BCM_SETSHIELD = (BCM_FIRST + 0x000C); //Elevated button #endregion Fields #region Methods public static bool amAdmin() { WindowsIdentity id = WindowsIdentity.GetCurrent(); WindowsPrincipal p = new WindowsPrincipal(id); return p.IsInRole(WindowsBuiltInRole.Administrator); }
public bool IsWarewolfAuthorised(string privilege, string userName, string resourceGuid) { userName = CleanUser(userName); IPrincipal identity; try { identity = new WindowsPrincipal(new WindowsIdentity(userName)); } catch (Exception) { var groups = GetLocalUserGroupsForTaskSchedule(userName); var tmp = new GenericIdentity(userName); identity = new GenericPrincipal(tmp, groups.ToArray()); } if (_authorizationService.IsAuthorized(identity, AuthorizationContext.Execute, resourceGuid)) { return true; } return false; }
public bool IsWindowsAuthorised(string privilege, string userName) { bool windowsAuthorised = false; userName = CleanUser(userName); var privileges = new LSA_UNICODE_STRING[1]; privileges[0] = InitLsaString(privilege); IntPtr buffer; ulong count; uint ret = Win32Sec.LsaEnumerateAccountsWithUserRight(lsaHandle, privileges, out buffer, out count); var Accounts = new List<String>(); if (ret == 0) { var LsaInfo = new LSA_ENUMERATION_INFORMATION[count]; LSA_ENUMERATION_INFORMATION myLsaus = new LSA_ENUMERATION_INFORMATION(); for (ulong i = 0; i < count; i++) { IntPtr itemAddr = new IntPtr(buffer.ToInt64() + (long)(i * (ulong)Marshal.SizeOf(myLsaus))); LsaInfo[i] = (LSA_ENUMERATION_INFORMATION)Marshal.PtrToStructure(itemAddr, myLsaus.GetType()); var SID = new SecurityIdentifier(LsaInfo[i].PSid); Accounts.Add(ResolveAccountName(SID)); } try { var wp = new WindowsPrincipal(new WindowsIdentity(userName)); foreach (string account in Accounts) { if (wp.IsInRole(account)) { windowsAuthorised = true; } } return windowsAuthorised; } catch (Exception) { var localGroups = GetLocalUserGroupsForTaskSchedule(userName); var intersection = localGroups.Intersect(Accounts); return intersection.Any(); } } return false; }
static void Main(string[] args) { try { var identity = WindowsIdentity.GetCurrent(); var principal = new WindowsPrincipal(identity); bool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); if (!isAdmin) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("This application must be run with administrator privileges!"); Console.ReadKey(); Environment.Exit(0); } } catch (Exception) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Unable to determine if this application is running with administrator privileges."); Console.WriteLine("Did you run it with administrator privileges? (Y=Yes,N=No)"); var ranAsAdmin = Console.ReadLine(); if (ranAsAdmin == null || ranAsAdmin.ToLower() != "y") { Environment.Exit(0); } } Console.WriteLine("Trying to find registry file to reset..."); try { var filePath = String.Format(@"{0}\sebregistry.srg", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); if (File.Exists(filePath)) { Console.WriteLine(String.Format("Found {0}", filePath)); Console.WriteLine("Resetting Registry keys..."); var service = new RegistryService(); if (service.Reset()) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Registry keys resetted successfully!"); Console.WriteLine("Press any key to exit application"); Console.ReadKey(); Environment.Exit(0); } else { Console.WriteLine("Unable to reset registry keys!"); } } Console.WriteLine("File not found!"); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(String.Format("Error: Unable to find file or reset registry keys\n{0}:{1}", ex.ToString(), ex.Message)); } //Direct Instantiation Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("If the file was not found, it is possible that there are no registry entries to reset.\nIs there anything NOT working as expected when you press CTRL+ALT+DEL? (Y=Yes/N=No)"); var res = Console.ReadLine(); if (res == null || res.ToLower() != "y") { Environment.Exit(0); } Console.WriteLine("Under what user did you run the SEB Windows Client? (Please type in the username followed by ENTER)"); var username = Console.ReadLine(); var sid = ""; try { sid = SIDHandler.GetSIDFromUsername(username); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("User not found in the registry!"); Console.ReadKey(); Environment.Exit(0); } Console.ResetColor(); Console.WriteLine("Resetting all registry entries possibly touched by the SEB Windows Service to an unrestricted value"); var entriesToZero = new List <RegistryEntry> { new RegDisableChangePassword(sid), new RegDisableLockWorkstation(sid), new RegDisableTaskMgr(sid), new RegHideFastUserSwitching(sid), new RegNoClose(sid), new RegNoLogoff(sid), new RegDontDisplayNetworkSelectionUI(sid) }; var entriesToOne = new List <RegistryEntry> { new RegEnableShade(sid) }; foreach (var entry in entriesToZero) { try { if (entry.DataValue != null) { entry.DataValue = 0; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(String.Format(@"Set {0}\{1} to {2}", entry.RegistryPath, entry.DataItemName, entry.DataValue)); } } catch (Exception) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(String.Format(@"Unable to set {0}\{1} to 0", entry.RegistryPath, entry.DataItemName)); } } foreach (var entry in entriesToOne) { try { if (entry.DataValue != null) { entry.DataValue = 1; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(String.Format(@"Set {0}\{1} to {2}", entry.RegistryPath, entry.DataItemName, entry.DataValue)); } } catch (Exception) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(String.Format(@"Unable to set {0}\{1} to 1", entry.RegistryPath, entry.DataItemName)); } } var easeOfAccess = new RegEaseOfAccess(sid); try { if (easeOfAccess.DataValue != null && easeOfAccess.DataValue.ToString() == "SebDummy.exe") { easeOfAccess.DataValue = ""; Console.WriteLine(String.Format(@"Set {0}\{1} to {2}", easeOfAccess.RegistryPath, easeOfAccess.DataItemName, easeOfAccess.DataValue)); } } catch (Exception) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(String.Format(@"Unable to set {0}\{1} to ''", easeOfAccess.RegistryPath, easeOfAccess.DataItemName)); } var enableShadeHorizon = new RegEnableShadeHorizon(sid); try { if (enableShadeHorizon.DataValue != null && enableShadeHorizon.DataValue.ToString() == "False") { enableShadeHorizon.DataValue = "True"; Console.WriteLine(String.Format(@"Set {0}\{1} to {2}", enableShadeHorizon.RegistryPath, enableShadeHorizon.DataItemName, enableShadeHorizon.DataValue)); } } catch (Exception) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(String.Format(@"Unable to set {0}\{1} to ''", enableShadeHorizon.RegistryPath, enableShadeHorizon.DataItemName)); } Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Finished, press any key to exit the application"); Console.ReadKey(); }
/// <summary> /// The function checks whether the primary access token of the process belongs /// to user account that is a member of the local Administrators group, even if /// it currently is not elevated. /// </summary> /// <returns> /// Returns true if the primary access token of the process belongs to user /// account that is a member of the local Administrators group. Returns false /// if the token does not. /// </returns> /// <exception cref="System.ComponentModel.Win32Exception"> /// When any native Windows API call fails, the function throws a Win32Exception /// with the last error code. /// </exception> internal bool IsUserInAdminGroup() { bool fInAdminGroup = false; SafeTokenHandle hToken = null; SafeTokenHandle hTokenToCheck = null; IntPtr pElevationType = IntPtr.Zero; IntPtr pLinkedToken = IntPtr.Zero; int cbSize = 0; try { // Open the access token of the current process for query and duplicate. if (!NativeMethods.OpenProcessToken(Process.GetCurrentProcess().Handle, NativeMethods.TOKEN_QUERY | NativeMethods.TOKEN_DUPLICATE, out hToken)) { throw new Win32Exception(); } // Determine whether system is running Windows Vista or later operating // systems (major version >= 6) because they support linked tokens, but // previous versions (major version < 6) do not. if (Environment.OSVersion.Version.Major >= 6) { // Running Windows Vista or later (major version >= 6). // Determine token type: limited, elevated, or default. // Allocate a buffer for the elevation type information. cbSize = sizeof(TOKEN_ELEVATION_TYPE); pElevationType = Marshal.AllocHGlobal(cbSize); if (pElevationType == IntPtr.Zero) { throw new Win32Exception(); } // Retrieve token elevation type information. if (!NativeMethods.GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenElevationType, pElevationType, cbSize, out cbSize)) { throw new Win32Exception(); } // Marshal the TOKEN_ELEVATION_TYPE enum from native to .NET. TOKEN_ELEVATION_TYPE elevType = (TOKEN_ELEVATION_TYPE) Marshal.ReadInt32(pElevationType); // If limited, get the linked elevated token for further check. if (elevType == TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited) { // Allocate a buffer for the linked token. cbSize = IntPtr.Size; pLinkedToken = Marshal.AllocHGlobal(cbSize); if (pLinkedToken == IntPtr.Zero) { throw new Win32Exception(); } // Get the linked token. if (!NativeMethods.GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenLinkedToken, pLinkedToken, cbSize, out cbSize)) { throw new Win32Exception(); } // Marshal the linked token value from native to .NET. IntPtr hLinkedToken = Marshal.ReadIntPtr(pLinkedToken); hTokenToCheck = new SafeTokenHandle(hLinkedToken); } } // CheckTokenMembership requires an impersonation token. If we just got // a linked token, it already is an impersonation token. If we did not // get a linked token, duplicate the original into an impersonation // token for CheckTokenMembership. if (hTokenToCheck == null) { if (!NativeMethods.DuplicateToken(hToken, SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, out hTokenToCheck)) { throw new Win32Exception(); } } // Check if the token to be checked contains admin SID. WindowsIdentity id = new WindowsIdentity(hTokenToCheck.DangerousGetHandle()); WindowsPrincipal principal = new WindowsPrincipal(id); fInAdminGroup = principal.IsInRole(WindowsBuiltInRole.Administrator); } finally { // Centralized cleanup for all allocated resources. if (hToken != null) { hToken.Close(); hToken = null; } if (hTokenToCheck != null) { hTokenToCheck.Close(); hTokenToCheck = null; } if (pElevationType != IntPtr.Zero) { Marshal.FreeHGlobal(pElevationType); pElevationType = IntPtr.Zero; } if (pLinkedToken != IntPtr.Zero) { Marshal.FreeHGlobal(pLinkedToken); pLinkedToken = IntPtr.Zero; } } return fInAdminGroup; }
public DataGridPrinter(DataGridView Grid) { //\\ Initialise the bits we need to use later _GridPrintDocument = new PrintDocument(); _DataGrid = Grid; WindowsPrincipal LoggedInuser = new WindowsPrincipal(WindowsIdentity.GetCurrent()); _LoggedInUsername = DataGridPrinter.StripDomainFromFullUsername(WindowsIdentity.GetCurrent().Name); }
private static bool RunAsAdministrator() { var identity = WindowsIdentity.GetCurrent(); var principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); }
public static bool IsAdministratorByToken(WindowsIdentity identity) { WindowsPrincipal principal = new WindowsPrincipal(identity); // Check if this user has the Administrator role. If they do, return immediately. // If UAC is on, and the process is not elevated, then this will actually return false. if (principal.IsInRole(WindowsBuiltInRole.Administrator)) { return(true); } // If we're not running in Vista onwards, we don't have to worry about checking for UAC. if (Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 6) { // Operating system does not support UAC; skipping elevation check. return(false); } int tokenInfLength = Marshal.SizeOf(typeof(int)); IntPtr tokenInformation = Marshal.AllocHGlobal(tokenInfLength); try { IntPtr token = identity.Token; Boolean result = WinApi.GetTokenInformation(token, WinApi.TokenInformationClass.TokenElevationType, tokenInformation, tokenInfLength, out tokenInfLength); if (!result) { Exception exception = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()); throw new InvalidOperationException("Couldn't get token information", exception); } WinApi.TokenElevationType elevationType = (WinApi.TokenElevationType)Marshal.ReadInt32(tokenInformation); switch (elevationType) { case WinApi.TokenElevationType.TokenElevationTypeDefault: // TokenElevationTypeDefault - User is not using a split token, so they cannot elevate. return(false); case WinApi.TokenElevationType.TokenElevationTypeFull: // TokenElevationTypeFull - User has a split token, and the process is running elevated. Assuming they're an administrator. return(true); case WinApi.TokenElevationType.TokenElevationTypeLimited: // TokenElevationTypeLimited - User has a split token, but the process is not running elevated. Assuming they're an administrator. return(true); default: // Unknown token elevation type. return(false); } } finally { if (tokenInformation != IntPtr.Zero) { Marshal.FreeHGlobal(tokenInformation); } } }
private void button5_Click(object sender, EventArgs e) { ipandtime.Clear(); WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); if (!principal.IsInRole(WindowsBuiltInRole.Administrator)) { NotAdminisortoRun nar = new NotAdminisortoRun(this); nar.ShowDialog(); if (!cannotad) { return; } } try { string path = AppDomain.CurrentDomain.BaseDirectory + "confforip.txt"; //获取文件内容 if (!System.IO.File.Exists(path)) { NeedConf nc = new NeedConf(); nc.Show(); return; } string[] ips = System.IO.File.ReadAllLines(path); ips = DelRepeatData(ips); ips = DelNullData(ips); Thread[] teskping = new Thread[ips.Count()]; for (int i = 0; i < ips.Count(); i++) { Thread sanip = new Thread(new ParameterizedThreadStart(ConnectIP)); sanip.Start(ips[i]); teskping[i] = sanip; } bool threadst = true; while (threadst) { bool iscon = true; for (int a = 0; a < teskping.Length; a++) { if (teskping[a] == null) { continue; } while (teskping[a].IsAlive && iscon) { iscon = false; } if (teskping[a].IsAlive == false) { ips[a] = null; } } if (ips.All(m => m == null)) { threadst = false; } } //电脑可能未连接网络成功 if (ipandtime == null) { Result rs = new Result(ErrorCode: 100003); rs.Show(); ipandtime.Clear(); return; } string needtobeip = ipandtime.First(a => a.Value == ipandtime.Values.Min()).Key; if (!System.IO.File.Exists("C:\\Windows\\System32\\drivers\\etc\\hosts")) { FileStream fs = new FileStream("C:\\Windows\\System32\\drivers\\etc\\hosts", FileMode.CreateNew); StreamWriter sw = new StreamWriter(fs); sw.WriteLine("\r\n" + needtobeip + "\tsteamcommunity.com"); sw.Flush(); sw.Close(); fs.Close(); } DelsteamcommHost(); FileStream fss = new FileStream("C:\\Windows\\System32\\drivers\\etc\\hosts", FileMode.Append); StreamWriter swer = new StreamWriter(fss); swer.WriteLine("\r\n" + needtobeip + "\tsteamcommunity.com"); swer.Flush(); swer.Close(); fss.Close(); Result r = new Result(ErrorCode: 0); r.Show(); return; } catch { Result rs = new Result(ErrorCode: 300001); rs.Show(); return; } }
private async Task <ClaimsPrincipal> SignInUsingLogonAsync(BasicSignInContext context) { var user = new StringBuilder(NativeMethods.CREDUI_MAX_USERNAME_LENGTH + 1); var domain = new StringBuilder(NativeMethods.CREDUI_MAX_DOMAIN_LENGTH + 1); uint error = NativeMethods.CredUIParseUserName(context.Username, user, user.Capacity, domain, domain.Capacity); if (error != 0) { _logger.LogError(Resources.Error_UserNameParse, context.Username, error.ToString("X")); return(null); } IntPtr token; WindowsIdentity winIdentity = null; string profilePath = string.Empty; _logger.LogTrace(Resources.Trace_LogOnUserBegin, context.Username); if (NativeMethods.LogonUser(user.ToString(), domain.ToString(), context.Password, (int)LogonType.LOGON32_LOGON_NETWORK, (int)LogonProvider.LOGON32_PROVIDER_DEFAULT, out token)) { _logger.LogTrace(Resources.Trace_LogOnSuccess, context.Username); winIdentity = new WindowsIdentity(token); StringBuilder profileDir = new StringBuilder(NativeMethods.MAX_PATH * 2); uint size = (uint)profileDir.Capacity; if (NativeMethods.GetUserProfileDirectory(token, profileDir, ref size)) { profilePath = profileDir.ToString(); _logger.LogTrace(Resources.Trace_UserProfileDirectory, context.Username, profilePath); } else { #if DEBUG CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromMinutes(10)); #else CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); #endif _logger.LogTrace(Resources.Trace_UserProfileCreation, context.Username); var result = await _userProfileManager.CreateProfileAsync(new RUserProfileServiceRequest(user.ToString(), domain.ToString(), winIdentity.User.Value), cts.Token); if (result.IsInvalidResponse()) { _logger.LogError(Resources.Error_ProfileCreationFailedInvalidResponse, context.Username, Resources.Info_UserProfileServiceName); return(null); } error = result.Error; // 0x800700b7 - Profile already exists. if (error != 0 && error != 0x800700b7) { _logger.LogError(Resources.Error_ProfileCreationFailed, context.Username, error.ToString("X")); return(null); } else if (error == 0x800700b7 || result.ProfileExists) { _logger.LogInformation(Resources.Info_ProfileAlreadyExists, context.Username); } else { _logger.LogInformation(Resources.Info_ProfileCreated, context.Username); } if (!string.IsNullOrEmpty(result.ProfilePath)) { profilePath = result.ProfilePath; _logger.LogTrace(Resources.Trace_UserProfileDirectory, context.Username, profilePath); } else { if (NativeMethods.GetUserProfileDirectory(token, profileDir, ref size)) { profilePath = profileDir.ToString(); _logger.LogTrace(Resources.Trace_UserProfileDirectory, context.Username, profilePath); } else { _logger.LogError(Resources.Error_GetUserProfileDirectory, context.Username, Marshal.GetLastWin32Error().ToString("X")); } } } } else { _logger.LogError(Resources.Error_LogOnFailed, context.Username, Marshal.GetLastWin32Error().ToString("X")); return(null); } var principal = new WindowsPrincipal(winIdentity); if (principal.IsInRole(_options.AllowedGroup)) { var claims = new[] { //new Claim(ClaimTypes.Name, context.Username), new Claim(Claims.RUser, ""), new Claim(Claims.RUserProfileDir, profilePath) }; var claimsIdentity = new ClaimsIdentity(claims, context.Options.AuthenticationScheme); principal.AddIdentities(new[] { claimsIdentity }); } return(principal); }
public static bool HasWritePermission(string FilePath) { try { if (!FilePath.Trim().EndsWith("\\")) { FilePath += @"\"; } FileSystemSecurity security; if (File.Exists(FilePath)) { security = File.GetAccessControl(FilePath); } else { security = Directory.GetAccessControl(System.IO.Path.GetDirectoryName(FilePath)); } var rules = security.GetAccessRules(true, true, typeof(NTAccount)); var currentUser = new WindowsPrincipal(WindowsIdentity.GetCurrent()); bool result = false; foreach (FileSystemAccessRule rule in rules) { if (0 == (rule.FileSystemRights & (FileSystemRights.WriteData | FileSystemRights.Write))) { continue; } if (rule.IdentityReference.Value.StartsWith("S-1-")) { var sid = new SecurityIdentifier(rule.IdentityReference.Value); if (!currentUser.IsInRole(sid)) { continue; } } else { if (!currentUser.IsInRole(rule.IdentityReference.Value)) { continue; } } if (rule.AccessControlType == AccessControlType.Deny) { return(false); } if (rule.AccessControlType == AccessControlType.Allow) { result = true; } } return(result); } catch { return(false); } }
private static void CheckWritePermission(string path) { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); bool isInRoleWithAccess = false; try { DirectoryInfo di = new DirectoryInfo(path); DirectorySecurity ds = di.GetAccessControl(); AuthorizationRuleCollection rules = ds.GetAccessRules(true, true, typeof(NTAccount)); foreach (AuthorizationRule rule in rules) { FileSystemAccessRule fsAccessRule = rule as FileSystemAccessRule; if (fsAccessRule == null) { continue; } if ((fsAccessRule.FileSystemRights & FileSystemRights.Write) != 0) { NTAccount ntAccount = rule.IdentityReference as NTAccount; if (ntAccount == null) { continue; } if (principal.IsInRole(ntAccount.Value)) { if (fsAccessRule.AccessControlType == AccessControlType.Deny) { isInRoleWithAccess = false; break; } isInRoleWithAccess = true; } } } } catch (UnauthorizedAccessException) { } if (!isInRoleWithAccess) { // is run as administrator? if (principal.IsInRole(WindowsBuiltInRole.Administrator)) { return; } // try run as admin Process proc = new Process(); string[] args = Environment.GetCommandLineArgs(); proc.StartInfo.FileName = args[0]; proc.StartInfo.Arguments = string.Join(" ", args.Skip(1).Select(t => $"\"{t}\"")); proc.StartInfo.UseShellExecute = true; proc.StartInfo.Verb = "runas"; try { proc.Start(); Environment.Exit(0); } catch (Win32Exception ex) { //The operation was canceled by the user. const int ERROR_CANCELLED = 1223; if (ex.NativeErrorCode == ERROR_CANCELLED) { Logger.Instance.Log(LogType.Error, LogCategory.General, $"You can't export to folder {path} without Administrator permission"); Console.ReadKey(); } else { Logger.Instance.Log(LogType.Error, LogCategory.General, $"You have to restart application as Administator in order to export to folder {path}"); Console.ReadKey(); } } } }
public async Task <SignInResponseMessage> GenerateAsync(SignInRequestMessage request, WindowsPrincipal windowsPrincipal) { Logger.Info("Creating WS-Federation signin response"); // create subject var outgoingSubject = SubjectGenerator.Create(windowsPrincipal, _options); // call custom claims tranformation logic var context = new CustomClaimsProviderContext { WindowsPrincipal = windowsPrincipal, OutgoingSubject = outgoingSubject }; await _options.CustomClaimsProvider.TransformAsync(context); // create token for user var token = CreateSecurityToken(context.OutgoingSubject); // return response var rstr = new RequestSecurityTokenResponse { AppliesTo = new EndpointReference(_options.IdpRealm), Context = request.Context, ReplyTo = _options.IdpReplyUrl, RequestedSecurityToken = new RequestedSecurityToken(token) }; var serializer = new WSFederationSerializer( new WSTrust13RequestSerializer(), new WSTrust13ResponseSerializer()); var mgr = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager(); mgr[SecurityTokenHandlerCollectionManager.Usage.Default] = CreateSupportedSecurityTokenHandler(); var responseMessage = new SignInResponseMessage( new Uri(_options.IdpReplyUrl), rstr, serializer, new WSTrustSerializationContext(mgr)); return(responseMessage); }
/// **************************************************************** /// public Main [static] /// ---------------------------------------------------------------- /// <summary> /// Program entry point. /// </summary> /// ---------------------------------------------------------------- /// <param name="args"> /// Command-line arguments. /// </param> /// **************************************************************** /// public static void Main(string[] args) { // // Use shared memory to make sure that only 1 instance of this process is running. sharedMemory.Release() MUST // be called when this process exits in order to free up the shared memory. // SharedMemory sharedMemory = new SharedMemory(); try { Console.WriteLine("Microsoft (R) UDDI Replication Utility"); Console.WriteLine("Copyright (C) Microsoft Corp. 2002. All rights reserved."); Console.WriteLine(); if (false == sharedMemory.Create("UDDI_replication_process")) { Console.WriteLine("Only 1 instance of this process can be running."); System.Environment.Exit(1); } WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); Context.User.SetRole(principal); if (!Context.User.IsAdministrator) { Console.WriteLine("Access denied.\r\n\r\nThis program must be executed by a member of the '" + Config.GetString("GroupName.Administrators") + "'\r\ngroup. The current user '" + identity.Name + "' is not a member of this group."); return; } ProcessCommandLine(args); ConnectionManager.Open(true, false); try { if (null == OperatorKey) { ReplicationHelper.Replicate(); } else { ReplicationHelper.ReplicateWithNode(OperatorKey); } } finally { ConnectionManager.Close(); } } catch (CommandLineException e) { if (null != e.Message && e.Message.Length > 0) { Console.WriteLine(e.Message); } else { DisplayUsage(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } finally { sharedMemory.Release(); } }
// Enumerates ds4 controllers in the system public static void findControllers() { lock (Devices) { IEnumerable <HidDevice> hDevices = HidDevices.EnumerateDS4(knownDevices); hDevices = hDevices.Where(dev => IsRealDS4(dev)).Select(dev => dev); //hDevices = from dev in hDevices where IsRealDS4(dev) select dev; // Sort Bluetooth first in case USB is also connected on the same controller. hDevices = hDevices.OrderBy <HidDevice, ConnectionType>((HidDevice d) => { return(DS4Device.HidConnectionType(d)); }); List <HidDevice> tempList = hDevices.ToList(); purgeHiddenExclusiveDevices(); tempList.AddRange(DisabledDevices); int devCount = tempList.Count(); string devicePlural = "device" + (devCount == 0 || devCount > 1 ? "s" : ""); //Log.LogToGui("Found " + devCount + " possible " + devicePlural + ". Examining " + devicePlural + ".", false); for (int i = 0; i < devCount; i++) //foreach (HidDevice hDevice in hDevices) { HidDevice hDevice = tempList[i]; if (hDevice.Description == "HID-compliant vendor-defined device") { continue; // ignore the Nacon Revolution Pro programming interface } else if (DevicePaths.Contains(hDevice.DevicePath)) { continue; // BT/USB endpoint already open once } VidPidInfo metainfo = knownDevices.Single(x => x.vid == hDevice.Attributes.VendorId && x.pid == hDevice.Attributes.ProductId); if (!hDevice.IsOpen) { hDevice.OpenDevice(isExclusiveMode); if (!hDevice.IsOpen && isExclusiveMode) { try { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); bool elevated = principal.IsInRole(WindowsBuiltInRole.Administrator); if (!elevated) { // Launches an elevated child process to re-enable device string exeName = Process.GetCurrentProcess().MainModule.FileName; ProcessStartInfo startInfo = new ProcessStartInfo(exeName); startInfo.Verb = "runas"; startInfo.Arguments = "re-enabledevice " + devicePathToInstanceId(hDevice.DevicePath); Process child = Process.Start(startInfo); if (!child.WaitForExit(30000)) { child.Kill(); } else if (child.ExitCode == 0) { hDevice.OpenDevice(isExclusiveMode); } } else { reEnableDevice(devicePathToInstanceId(hDevice.DevicePath)); hDevice.OpenDevice(isExclusiveMode); } } catch (Exception) { } } // TODO in exclusive mode, try to hold both open when both are connected if (isExclusiveMode && !hDevice.IsOpen) { hDevice.OpenDevice(false); } } if (hDevice.IsOpen) { string serial = hDevice.readSerial(); bool validSerial = !serial.Equals(DS4Device.blankSerial); if (validSerial && deviceSerials.Contains(serial)) { // happens when the BT endpoint already is open and the USB is plugged into the same host if (isExclusiveMode && hDevice.IsExclusive && !DisabledDevices.Contains(hDevice)) { // Grab reference to exclusively opened HidDevice so device // stays hidden to other processes DisabledDevices.Add(hDevice); //DevicePaths.Add(hDevice.DevicePath); } continue; } else { DS4Device ds4Device = new DS4Device(hDevice, metainfo.name); //ds4Device.Removal += On_Removal; if (!ds4Device.ExitOutputThread) { Devices.Add(hDevice.DevicePath, ds4Device); DevicePaths.Add(hDevice.DevicePath); deviceSerials.Add(serial); } } } } } }
private void EmulateWindowsAuthentication(HttpApplication application) { WindowsIdentity identity = null; if (HttpRuntime.UsingIntegratedPipeline) { WindowsPrincipal user = null; if (HttpRuntime.IsOnUNCShare && application.Request.IsAuthenticated) { IntPtr applicationIdentityToken = (IntPtr)typeof(System.Web.Hosting.HostingEnvironment).GetProperty("ApplicationIdentityToken", BindingFlags.NonPublic | BindingFlags.Static).GetGetMethod().Invoke(null, null); WindowsIdentity wi = new WindowsIdentity(applicationIdentityToken, application.User.Identity.AuthenticationType, WindowsAccountType.Normal, true); user = new WindowsPrincipal(wi); } else { user = application.Context.User as WindowsPrincipal; } if (user != null) { identity = user.Identity as WindowsIdentity; object[] setPrincipalNoDemandParameters = new object[] { null, false }; Type[] setPrincipalNoDemandParameterTypes = new Type[] { typeof(IPrincipal), typeof(bool) }; MethodInfo setPrincipalNoDemandMethodInfo = application.Context.GetType().GetMethod("SetPrincipalNoDemand", BindingFlags.Instance | BindingFlags.NonPublic, null, setPrincipalNoDemandParameterTypes, null); setPrincipalNoDemandMethodInfo.Invoke(application.Context, setPrincipalNoDemandParameters); } } else { HttpWorkerRequest workerRequest = (HttpWorkerRequest)application.Context.GetType().GetProperty("WorkerRequest", BindingFlags.NonPublic | BindingFlags.Instance).GetGetMethod(true).Invoke(application.Context, null); string logonUser = workerRequest.GetServerVariable("LOGON_USER"); string authType = workerRequest.GetServerVariable("AUTH_TYPE"); if (logonUser == null) { logonUser = string.Empty; } if (authType == null) { authType = string.Empty; } if (logonUser.Length == 0 && authType.Length == 0 || authType.ToLower() == "basic") { identity = WindowsIdentity.GetAnonymous(); } else { identity = new WindowsIdentity(workerRequest.GetUserToken(), authType, System.Security.Principal.WindowsAccountType.Normal, true); } } if (identity != null) { WindowsPrincipal wp = new WindowsPrincipal(identity); object[] setPrincipalNoDemandParameters = new object[] { wp, false }; Type[] setPrincipalNoDemandParameterTypes = new Type[] { typeof(IPrincipal), typeof(bool) }; MethodInfo setPrincipalNoDemandMethodInfo = application.Context.GetType().GetMethod("SetPrincipalNoDemand", BindingFlags.Instance | BindingFlags.NonPublic, null, setPrincipalNoDemandParameterTypes, null); setPrincipalNoDemandMethodInfo.Invoke(application.Context, setPrincipalNoDemandParameters); } // return 401 if user is not authenticated: // - application.Context.User might be null for ContentStore GetTreeNodeAllChildren?... request // - currentPortalUser.Id might be startupuserid or visitoruserid if browser did not send 'negotiate' auth header yet // - currentPortalUser might be null if application.Context.User.Identity is null or not an IUser IUser currentPortalUser = null; if (application.Context.User != null) { currentPortalUser = application.Context.User.Identity as IUser; } if ((application.Context.User == null) || (currentPortalUser != null && (currentPortalUser.Id == Identifiers.StartupUserId || currentPortalUser.Id == Identifiers.VisitorUserId))) { if (!IsLocalAxdRequest()) { AuthenticationHelper.DenyAccess(application); } return; } }
private bool HasAdminRights() { WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); return(pricipal.IsInRole(WindowsBuiltInRole.Administrator)); }
private static void Main(string[] args) { try { logo(); // https://github.com/GhostPack/Rubeus/blob/master/Rubeus/Domain/ArgumentParser.cs#L10 var arguments = new Dictionary <string, string>(); foreach (var argument in args) { var idx = argument.IndexOf(':'); if (idx > 0) { arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1); } else { arguments[argument] = string.Empty; } } WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); if (principal.IsInRole(WindowsBuiltInRole.Administrator)) { Console.WriteLine($"[+] Process running with {principal.Identity.Name} privileges with HIGH integrity."); } else { Console.WriteLine($"[+] Process running with {principal.Identity.Name} privileges with MEDIUM / LOW integrity."); } if (arguments.Count == 0) { Console.WriteLine("[+] No arguments specified. Please refer the help section for more details."); help(); } else if (arguments.ContainsKey("/pname")) { Process[] process = Process.GetProcessesByName(arguments["/pname"]); if (process.Length > 0) { for (int i = 0; i < process.Length; i++) { Console.WriteLine($"[+] Dumping {process[i].ProcessName} process"); Console.WriteLine($"[+] {process[i].ProcessName} process handler {process[i].Handle}"); Console.WriteLine($"[+] {process[i].ProcessName} process id {process[i].Id}"); dump(process[i].Handle, (uint)process[i].Id, process[i].ProcessName); } } else { Console.WriteLine($"[+] {arguments["/pname"]} process is not running."); } } else if (arguments.ContainsKey("/pid")) { int procid = Convert.ToInt32(arguments["/pid"]); Process process = Process.GetProcessById(procid); Console.WriteLine($"[+] Dumping {process.ProcessName} process"); Console.WriteLine($"[+] {process.ProcessName} process handler {process.Handle}"); Console.WriteLine($"[+] {process.ProcessName} process id {process.Id}"); dump(process.Handle, (uint)process.Id, process.ProcessName); } else { Console.WriteLine("[+] Invalid argument. Please refer the help section for more details."); help(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); }
public static JObject ProgramInfoJsonGet() { WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); bool isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator); JObject jContent = new JObject { { "application", new JObject { { "isElevated", Convert.ToString(isElevated) }, { "lastUpdateCheck", appSettings.Tool_LastCheckForUpdates }, { "version", AppVersion.ToString() } } }, { "config", new JObject { { "chosenDownloadMirror", appSettings.Tool_ChosenDownloadMirror }, { "updateInterval", appSettings.Tool_CheckForUpdates.ToString() } } }, { "language", new JObject { { "code", appSettings.Tool_Language } } }, { "system", new JObject { { "cultureInfo", System.Globalization.CultureInfo.CurrentCulture.ToString() }, { "is64bit", Convert.ToString(Environment.Is64BitOperatingSystem) }, { "operatingSystem", Environment.OSVersion.Version.ToString() } } } }; return(jContent); }
/// <summary> /// Checks whether the client has specific file system rights to a directory. /// See ssds's answer at https://stackoverflow.com/questions/1410127/c-sharp-test-if-user-has-write-access-to-a-folder /// </summary> /// <param name="path">The path to the directory.</param> /// <param name="accessRights">The file system rights.</param> private static bool UserHasDirectoryAccessRights(string path, FileSystemRights accessRights) { #if WINDOWSGL // Mono doesn't implement everything necessary for the below to work, // so we'll just return to make the client able to run on non-Windows // platforms // On Windows you rarely have a reason for using the OpenGL build anyway return(true); #endif #pragma warning disable 0162 var currentUser = WindowsIdentity.GetCurrent(); #pragma warning restore 0162 var principal = new WindowsPrincipal(currentUser); // If the user is not running the client with administrator privileges in Program Files, they need to be prompted to do so. if (!principal.IsInRole(WindowsBuiltInRole.Administrator)) { string progfiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); string progfilesx86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); if (Environment.CurrentDirectory.Contains(progfiles) || Environment.CurrentDirectory.Contains(progfilesx86)) { return(false); } } var isInRoleWithAccess = false; try { var di = new DirectoryInfo(path); var acl = di.GetAccessControl(); var rules = acl.GetAccessRules(true, true, typeof(NTAccount)); foreach (AuthorizationRule rule in rules) { var fsAccessRule = rule as FileSystemAccessRule; if (fsAccessRule == null) { continue; } if ((fsAccessRule.FileSystemRights & accessRights) > 0) { var ntAccount = rule.IdentityReference as NTAccount; if (ntAccount == null) { continue; } if (principal.IsInRole(ntAccount.Value)) { if (fsAccessRule.AccessControlType == AccessControlType.Deny) { return(false); } isInRoleWithAccess = true; } } } } catch (UnauthorizedAccessException) { return(false); } return(isInRoleWithAccess); }
//将用户上一次的输入保存在txt中当用户下次启动程序读取 public void autoWriter(string path) { FileStream fs = new FileStream(path, FileMode.Create); StreamWriter sw = new StreamWriter(fs); ArrayList autoSave = new ArrayList(); WindowsIdentity wid = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(wid); string path1 = Application.ExecutablePath; RegistryKey rk = Registry.LocalMachine; if (principal.IsInRole(WindowsBuiltInRole.Administrator)) { if ((this.radioButton1.Checked == true) && (this.autoStart.Checked == true)) { this.plAdd.Text = ""; this.plPort.Text = ""; autoSave.Add(this.wltAdd.Text.Trim() + ","); autoSave.Add(this.minName.Text.Trim() + ","); autoSave.Add(this.maxTemp.Text.Trim() + ","); autoSave.Add(this.plAdd1.Text.Trim()); autoSave.Add(this.plPort1.Text.Trim()); autoSave.Add(this.autoStart.Checked); sw.Write(autoSave[0]); sw.Write(autoSave[1]); sw.Write(autoSave[2]); sw.Write(autoSave[3] = this.plAdd1.Text); sw.Write(autoSave[4] = "," + this.plPort1.Text); sw.Write(autoSave[5] = "," + this.autoStart.Checked); //motify MessageBox.Show("设置开机自启动设置成功,需要修改注册表,重启后执行", "提示"); RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"); rk2.SetValue("requestJson", path1); rk2.Close(); rk.Close(); } else if ((this.radioButton2.Checked == true) && (this.autoStart.Checked == true)) { this.plAdd1.Text = ""; this.plPort1.Text = ""; autoSave.Add(this.wltAdd.Text.Trim() + "|"); autoSave.Add(this.minName.Text.Trim() + "|"); autoSave.Add(this.maxTemp.Text.Trim() + "|"); autoSave.Add(this.plAdd.Text.Trim()); autoSave.Add(this.plPort.Text.Trim()); autoSave.Add(this.autoStart.Checked); sw.Write(autoSave[0]); sw.Write(autoSave[1]); sw.Write(autoSave[2]); sw.Write(autoSave[3] = this.plAdd.Text.Trim()); sw.Write(autoSave[4] = "|" + this.plPort.Text); sw.Write(autoSave[5] = "|" + this.autoStart.Checked); MessageBox.Show("设置开机自启动设置成功,需要修改注册表,重启后执行", "提示"); RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"); rk2.SetValue("requestJson", path1); rk2.Close(); rk.Close(); } else if ((this.radioButton1.Checked == true) && (this.autoStart.Checked == false)) { this.plAdd.Text = ""; this.plPort.Text = ""; autoSave.Add(this.wltAdd.Text.Trim() + ","); autoSave.Add(this.minName.Text.Trim() + ","); autoSave.Add(this.maxTemp.Text.Trim() + ","); autoSave.Add(this.plAdd1.Text.Trim()); autoSave.Add(this.plPort1.Text.Trim()); autoSave.Add(this.autoStart.Checked); sw.Write(autoSave[0]); sw.Write(autoSave[1]); sw.Write(autoSave[2]); sw.Write(autoSave[3] = this.plAdd1.Text); sw.Write(autoSave[4] = "," + this.plPort1.Text); sw.Write(autoSave[5] = "," + this.autoStart.Checked); MessageBox.Show("开机启动取消成功,需要修改注册表,重启后执行", "提示"); RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"); rk2.DeleteValue("requestJson", false); rk2.Close(); rk.Close(); } else if ((this.radioButton2.Checked == true) && (this.autoStart.Checked == false)) { this.plAdd1.Text = ""; this.plPort1.Text = ""; autoSave.Add(this.wltAdd.Text.Trim() + "|"); autoSave.Add(this.minName.Text.Trim() + "|"); autoSave.Add(this.maxTemp.Text.Trim() + "|"); autoSave.Add(this.plAdd.Text.Trim()); autoSave.Add(this.plPort.Text.Trim()); autoSave.Add(this.autoStart.Checked); sw.Write(autoSave[0]); sw.Write(autoSave[1]); sw.Write(autoSave[2]); sw.Write(autoSave[3] = this.plAdd.Text.Trim()); sw.Write(autoSave[4] = "|" + this.plPort.Text); sw.Write(autoSave[5] = "|" + this.autoStart.Checked); MessageBox.Show("开机启动取消成功,需要修改注册表,重启后执行", "提示"); RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"); rk2.DeleteValue("requestJson", false); rk2.Close(); rk.Close(); } } else { if ((this.radioButton1.Checked == true) && (this.autoStart.Checked == true)) { this.plAdd.Text = ""; this.plPort.Text = ""; autoSave.Add(this.wltAdd.Text.Trim() + ","); autoSave.Add(this.minName.Text.Trim() + ","); autoSave.Add(this.maxTemp.Text.Trim() + ","); autoSave.Add(this.plAdd1.Text.Trim()); autoSave.Add(this.plPort.Text.Trim()); autoSave.Add(this.autoStart.Checked); sw.Write(autoSave[0]); sw.Write(autoSave[1]); sw.Write(autoSave[2]); sw.Write(autoSave[3] = this.plAdd1.Text.Trim()); sw.Write(autoSave[4] = "," + this.plPort1.Text); sw.Write(autoSave[5] = "," + this.autoStart.Checked); } else if ((this.radioButton2.Checked == true) && (this.autoStart.Checked == true)) { this.plAdd1.Text = ""; this.plPort1.Text = ""; autoSave.Add(this.wltAdd.Text.Trim() + "|"); autoSave.Add(this.minName.Text.Trim() + "|"); autoSave.Add(this.maxTemp.Text.Trim() + "|"); autoSave.Add(this.plAdd.Text.Trim()); autoSave.Add(this.plPort.Text.Trim()); autoSave.Add(this.autoStart.Checked); sw.Write(autoSave[0]); sw.Write(autoSave[1]); sw.Write(autoSave[2]); sw.Write(autoSave[3] = this.plAdd.Text.Trim()); sw.Write(autoSave[4] = "|" + this.plPort.Text); sw.Write(autoSave[5] = "|" + this.autoStart.Checked); } else if ((this.radioButton1.Checked == true) && (this.autoStart.Checked == false)) { this.plAdd.Text = ""; this.plPort.Text = ""; autoSave.Add(this.wltAdd.Text.Trim() + ","); autoSave.Add(this.minName.Text.Trim() + ","); autoSave.Add(this.maxTemp.Text.Trim() + ","); autoSave.Add(this.plAdd1.Text.Trim()); autoSave.Add(this.plPort1.Text.Trim()); autoSave.Add(this.autoStart.Checked); sw.Write(autoSave[0]); sw.Write(autoSave[1]); sw.Write(autoSave[2]); sw.Write(autoSave[3] = this.plAdd1.Text.Trim()); sw.Write(autoSave[4] = "," + this.plPort1.Text); sw.Write(autoSave[5] = "," + this.autoStart.Checked); } else if ((this.radioButton2.Checked == true) && (this.autoStart.Checked == false)) { this.plAdd1.Text = ""; this.plPort1.Text = ""; autoSave.Add(this.wltAdd.Text.Trim() + "|"); autoSave.Add(this.minName.Text.Trim() + "|"); autoSave.Add(this.maxTemp.Text.Trim() + "|"); autoSave.Add(this.plAdd.Text.Trim()); autoSave.Add(this.plPort.Text.Trim()); autoSave.Add(this.autoStart.Checked); sw.Write(autoSave[0]); sw.Write(autoSave[1]); sw.Write(autoSave[2]); sw.Write(autoSave[3] = this.plAdd.Text.Trim()); sw.Write(autoSave[4] = "|" + this.plPort.Text); sw.Write(autoSave[5] = "|" + this.autoStart.Checked); } else { MessageBox.Show("首次使用请设置好参数"); } } //开始写入 //清空缓冲区 //sw.Flush(); //关闭流 sw.Flush(); sw.Close(); sw.Dispose(); fs.Close(); fs.Dispose(); }
public static void RestartService(string serviceName, int timeoutMilliseconds) { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); bool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); if (!isAdmin) { MessageBox.Show("Please run as administrator.", "HRDsq Plugin", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { HRDsqData.Library.WriteErrorLog("10"); ServiceController service = new ServiceController(serviceName); Connection conn = new Connection(); conn.RestartConnection(); HRDsqData.Library.WriteErrorLog("10"); int millisec1 = Environment.TickCount; TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); HRDsqData.Library.WriteErrorLog("11 " + timeout); try { HRDsqData.Library.WriteErrorLog("12 " + service.Status); switch (service.Status) { case ServiceControllerStatus.Running: { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); // count the rest of the timeout int millisec2 = Environment.TickCount; timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1)); service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); MessageBox.Show("HRDsq Service Restart Successfully.", "HRDsq Program", MessageBoxButtons.OK, MessageBoxIcon.Information); } break; case ServiceControllerStatus.Stopped: { service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); MessageBox.Show("HRDsq Service Restart Successfully.", "HRDsq Program", MessageBoxButtons.OK, MessageBoxIcon.Information); } break; case ServiceControllerStatus.Paused: { service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); MessageBox.Show("HRDsq Service Restart Successfully.", "HRDsq Program", MessageBoxButtons.OK, MessageBoxIcon.Information); } break; case ServiceControllerStatus.StopPending: break; case ServiceControllerStatus.StartPending: break; // default: } } catch (Exception ex) { MessageBox.Show("Error- " + ex.Message, "HRDsq Program", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
public static string RunStandardBotKiller() { string str2; int num2; try { int num3; Label_0001: ProjectData.ClearProjectError(); int num = -2; Label_000A: num3 = 2; WindowsIdentity current = WindowsIdentity.GetCurrent(); Label_0013: num3 = 3; WindowsPrincipal principal = new WindowsPrincipal(current); Label_001D: num3 = 4; IsAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); Label_0030: num3 = 5; ScanProcess(); Label_0039: num3 = 6; RunStartupKiller(); Label_0042: num3 = 7; string str = ProccessKilled.ToString() + "|S|" + Startupkilled.ToString(); Label_0064: num3 = 8; ProccessKilled = 0; Label_006D: num3 = 9; Startupkilled = 0; Label_0077: num3 = 10; str2 = str; goto Label_0114; Label_008F: num2 = 0; switch ((num2 + 1)) { case 1: goto Label_0001; case 2: goto Label_000A; case 3: goto Label_0013; case 4: goto Label_001D; case 5: goto Label_0030; case 6: goto Label_0039; case 7: goto Label_0042; case 8: goto Label_0064; case 9: goto Label_006D; case 10: goto Label_0077; case 11: goto Label_0114; default: goto Label_0109; } Label_00C9: num2 = num3; switch (((num > -2) ? num : 1)) { case 0: goto Label_0109; case 1: goto Label_008F; } } catch (object obj1) when(?) { ProjectData.SetProjectError((Exception)obj1); goto Label_00C9; } Label_0109: throw ProjectData.CreateProjectError(-2146828237); Label_0114: if (num2 != 0) { ProjectData.ClearProjectError(); } return(str2); }
/// <summary> /// Connects to the specified COM server server. /// </summary> public object CreateServer(Uri uri, UserIdentity identity) { // parse path to find prog id and clsid. string progID = uri.LocalPath; string clsid = null; while (progID.StartsWith("/")) { progID = progID.Substring(1); } int index = progID.IndexOf('/'); if (index >= 0) { clsid = progID.Substring(index + 1); progID = progID.Substring(0, index); } // look up prog id if clsid not specified in the uri. Guid guid = Guid.Empty; if (String.IsNullOrEmpty(clsid)) { // connect to enumerator. Connect(uri.Host, identity); // use OpcEnum to lookup the prog id. guid = CLSIDFromProgID(progID); // check if prog id is actually a clsid string. if (guid == Guid.Empty) { clsid = progID; } } // convert CLSID to a GUID. if (guid == Guid.Empty) { try { guid = new Guid(clsid); } catch (Exception e) { throw ServiceResultException.Create(StatusCodes.BadCommunicationError, e, "COM server URI does not contain a valid CLSID or ProgID."); } } // use normal activation. return(ComUtils.CreateInstance(guid, uri.Host, identity)); #if COM_IMPERSONATION_SUPPORT // set the current thread token. IPrincipal existingPrincipal = Thread.CurrentPrincipal; WindowsPrincipal principal = ComUtils.GetPrincipalFromUserIdentity(identity); try { if (principal != null) { Thread.CurrentPrincipal = principal; } // activate with a license key if one provided. if (identity != null && !String.IsNullOrEmpty(identity.LicenseKey)) { return(ComUtils.CreateInstanceWithLicenseKey(guid, uri.Host, identity, identity.LicenseKey)); } // use normal activation. return(ComUtils.CreateInstance(guid, uri.Host, identity)); } finally { Thread.CurrentPrincipal = existingPrincipal; } #endif }
static void Main(string[] args) { Application.EnableVisualStyles(); // Check for admin rights. WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); bool isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator); // names and paths string toolboxdir = Environment.GetEnvironmentVariable("LocalAppData") + Path.DirectorySeparatorChar + "GWToolboxpp" + Path.DirectorySeparatorChar; string inifile = toolboxdir + "GWToolbox.ini"; string dllfile = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + DLL_NAME; // Install resources ResInstaller installer = new ResInstaller(); installer.Install(); // Download or update if needed. If dll file exists in current directory, use it. if (!File.Exists(dllfile)) { dllfile = toolboxdir + DLL_NAME; } if (File.Exists(dllfile) && (new FileInfo(dllfile).Length) < 1) { File.Delete(dllfile); // Delete file if exists with 0 length } if (!File.Exists(dllfile)) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; WebClient host = new WebClient(); host.Headers.Add(HttpRequestHeader.UserAgent, "GWToolboxpp Launcher"); string remoteversion = GetLatestVersion(); if (remoteversion.Length == 0) { MessageBox.Show("Failed to fetch latest GWToolbox++ version.\n Check your internet connection and try again", "GWToolbox++ Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string dllurl = "https://github.com/" + GITHUB_USER + "/GWToolboxpp/releases/download/" + remoteversion + "_Release/" + DLL_NAME; int tries = 0; // This bit will take a while... while (tries < 3 && dllurl.Length > 0 && !File.Exists(dllfile)) { try { host.DownloadFile(dllurl, dllfile); if (File.Exists(dllfile) && (new System.IO.FileInfo(dllfile).Length) < 1) { File.Delete(dllfile); // Delete file if exists with 0 length } } catch (Exception) { // todo } tries++; } if (!File.Exists(dllfile)) { MessageBox.Show("Failed to download GWToolbox++ dll.\n Check your internet connection and try again", "GWToolbox++ Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } // check again after download/update/build if (!File.Exists(dllfile)) { MessageBox.Show("Cannot find " + DLL_NAME, "GWToolbox++ Launcher Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Look for gw processes. List <Process> processesToInject = new List <Process>(); CharSelector chargui = new CharSelector(); Process[] gwprocs = chargui.GetValidProcesses(); switch (gwprocs.Length) { case 0: // No gw processes found. if (!isElevated && hasElevatedGWProcesses()) { MessageBox.Show("Guild Wars is running as Admin.\n" + "Restart Guild Wars without Admin, or run this launcher as Admin to run GWToolbox++", "GWToolbox++ Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } MessageBox.Show("No Guild Wars clients found.\n" + "Please log into Guild Wars first.", "GWToolbox++ Error", MessageBoxButtons.OK, MessageBoxIcon.Error); break; case 1: // Only one process found, injecting. processesToInject.Add(gwprocs[0]); break; default: // More than one found, make user select client. Application.Run(chargui); processesToInject.AddRange(chargui.SelectedProcesses); break; } if (processesToInject.Count == 0) { return; } for (int i = 0; i < processesToInject.Count; ++i) { IntPtr dll_return; GWCAMemory mem = new GWCAMemory(processesToInject[i]); GWCAMemory.LOADMODULERESULT result = mem.LoadModule(dllfile, out dll_return); if (result == GWCAMemory.LOADMODULERESULT.SUCCESSFUL && dll_return != IntPtr.Zero) { // continue } else if (result == GWCAMemory.LOADMODULERESULT.SUCCESSFUL) { MessageBox.Show("Error loading DLL: ExitCode " + dll_return, "GWToolbox++ Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show("Module Load Error.\n" + LOADMODULE_RESULT_MESSAGES[(uint)result] + "\n", "GWToolbox++ Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } }
/// <summary> /// The function checks whether the primary access token of the process belongs /// to user account that is a member of the local Administrators group, even if /// it currently is not elevated. /// </summary> /// <returns> /// Returns true if the primary access token of the process belongs to user /// account that is a member of the local Administrators group. Returns false /// if the token does not. /// </returns> /// <exception cref="System.ComponentModel.Win32Exception"> /// When any native Windows API call fails, the function throws a Win32Exception /// with the last error code. /// </exception> public static bool IsUserInAdminGroup() { bool fInAdminGroup = false; SafeTokenHandle hToken = null; SafeTokenHandle hTokenToCheck = null; IntPtr pElevationType = IntPtr.Zero; IntPtr pLinkedToken = IntPtr.Zero; int cbSize = 0; try { // Open the access token of the current process for query and duplicate. if (!NativeMethods.OpenProcessToken(Process.GetCurrentProcess().Handle, NativeMethods.TOKEN_QUERY | NativeMethods.TOKEN_DUPLICATE, out hToken)) { throw new Win32Exception(); } // Determine whether system is running Windows Vista or later operating // systems (major version >= 6) because they support linked tokens, but // previous versions (major version < 6) do not. if (Environment.OSVersion.Version.Major >= 6) { // Running Windows Vista or later (major version >= 6). // Determine token type: limited, elevated, or default. // Allocate a buffer for the elevation type information. cbSize = sizeof(TOKEN_ELEVATION_TYPE); pElevationType = Marshal.AllocHGlobal(cbSize); if (pElevationType == IntPtr.Zero) { throw new Win32Exception(); } // Retrieve token elevation type information. if (!NativeMethods.GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenElevationType, pElevationType, cbSize, out cbSize)) { throw new Win32Exception(); } // Marshal the TOKEN_ELEVATION_TYPE enum from native to .NET. TOKEN_ELEVATION_TYPE elevType = (TOKEN_ELEVATION_TYPE) Marshal.ReadInt32(pElevationType); // If limited, get the linked elevated token for further check. if (elevType == TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited) { // Allocate a buffer for the linked token. cbSize = IntPtr.Size; pLinkedToken = Marshal.AllocHGlobal(cbSize); if (pLinkedToken == IntPtr.Zero) { throw new Win32Exception(); } // Get the linked token. if (!NativeMethods.GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenLinkedToken, pLinkedToken, cbSize, out cbSize)) { throw new Win32Exception(); } // Marshal the linked token value from native to .NET. IntPtr hLinkedToken = Marshal.ReadIntPtr(pLinkedToken); hTokenToCheck = new SafeTokenHandle(hLinkedToken); } } // CheckTokenMembership requires an impersonation token. If we just got // a linked token, it already is an impersonation token. If we did not // get a linked token, duplicate the original into an impersonation // token for CheckTokenMembership. if (hTokenToCheck == null) { if (!NativeMethods.DuplicateToken(hToken, SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, out hTokenToCheck)) { throw new Win32Exception(); } } // Check if the token to be checked contains admin SID. WindowsIdentity id = new WindowsIdentity(hTokenToCheck.DangerousGetHandle()); WindowsPrincipal principal = new WindowsPrincipal(id); fInAdminGroup = principal.IsInRole(WindowsBuiltInRole.Administrator); } finally { // Centralized cleanup for all allocated resources. if (hToken != null) { hToken.Close(); hToken = null; } if (hTokenToCheck != null) { hTokenToCheck.Close(); hTokenToCheck = null; } if (pElevationType != IntPtr.Zero) { Marshal.FreeHGlobal(pElevationType); pElevationType = IntPtr.Zero; } if (pLinkedToken != IntPtr.Zero) { Marshal.FreeHGlobal(pLinkedToken); pLinkedToken = IntPtr.Zero; } } return(fInAdminGroup); }
private static NamedPipeServerStream ConnectNamedPipe( string inOutPipeName, string outPipeName, out NamedPipeServerStream outPipe) { // .NET Core implementation is simplest so try that first if (Utils.IsNetCore) { outPipe = outPipeName == null ? null : new NamedPipeServerStream( pipeName: outPipeName, direction: PipeDirection.Out, maxNumberOfServerInstances: 1, transmissionMode: PipeTransmissionMode.Byte, options: (PipeOptions)CurrentUserOnly); return(new NamedPipeServerStream( pipeName: inOutPipeName, direction: PipeDirection.InOut, maxNumberOfServerInstances: 1, transmissionMode: PipeTransmissionMode.Byte, options: PipeOptions.Asynchronous | (PipeOptions)CurrentUserOnly)); } // Now deal with Windows PowerShell // We need to use reflection to get a nice constructor PipeSecurity pipeSecurity = new PipeSecurity(); WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); if (principal.IsInRole(WindowsBuiltInRole.Administrator)) { // Allow the Administrators group full access to the pipe. pipeSecurity.AddAccessRule(new PipeAccessRule( new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null).Translate(typeof(NTAccount)), PipeAccessRights.FullControl, AccessControlType.Allow)); } else { // Allow the current user read/write access to the pipe. pipeSecurity.AddAccessRule(new PipeAccessRule( WindowsIdentity.GetCurrent().User, PipeAccessRights.ReadWrite, AccessControlType.Allow)); } outPipe = outPipeName == null ? null : (NamedPipeServerStream)s_netFrameworkPipeServerConstructor.Invoke( new object[] { outPipeName, PipeDirection.InOut, 1, // maxNumberOfServerInstances PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, // inBufferSize 1024, // outBufferSize pipeSecurity }); return((NamedPipeServerStream)s_netFrameworkPipeServerConstructor.Invoke( new object[] { inOutPipeName, PipeDirection.InOut, 1, // maxNumberOfServerInstances PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, // inBufferSize 1024, // outBufferSize pipeSecurity })); }
public static bool HasAdministrativeRight() { var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); return(principal.IsInRole(WindowsBuiltInRole.Administrator)); }
/// <summary> /// ���݊Ǘ��Ҍ����Ŏ��s����Ă��邩�m�F���܂� /// </summary> /// <returns>�Ǘ��Ҍ����̏ꍇ��true, ��ʃ��[�U�̏ꍇ��false</returns> public static bool isAdmin() { WindowsIdentity usrId = WindowsIdentity.GetCurrent(); WindowsPrincipal p = new WindowsPrincipal(usrId); return p.IsInRole(@"BUILTIN\Administrators"); }