コード例 #1
0
ファイル: Permission.cs プロジェクト: rgshare/code-snippets
 /// <summary>
 /// 设置Everyone的写入权限
 /// </summary>
 static void SetControls(FileInfo file)
 {
     var everyOneIdentity = new NTAccount("Everyone");
     var everyoneAce = new FileSystemAccessRule(everyOneIdentity, FileSystemRights.Write, AccessControlType.Allow);
     var securityDescriptor = new FileSecurity();
     securityDescriptor.SetAccessRule(everyoneAce);
     file.SetAccessControl(securityDescriptor);
 }
コード例 #2
0
	public void ResetAccessRule(FileSystemAccessRule rule) {}
コード例 #3
0
 private static bool CheckAccessRuleLocal(FileSystemAccessRule fileSystemAccessRule, FileSystemRights fileSystemRights)
 {
     return((fileSystemRights & fileSystemAccessRule.FileSystemRights) == fileSystemRights);
 }
コード例 #4
0
        private void butOK_Click(object sender, System.EventArgs e)
        {
            if (!Directory.Exists(textLocation.Text))
            {
                MsgBox.Show(this, "Location does not exist.");
                return;
            }
            if (Directory.Exists(ODFileUtils.CombinePaths(textLocation.Text, textName.Text)))
            {
                MsgBox.Show(this, "Folder already exists.");
                return;
            }
            try {
                FileSystemAccessRule fsar = new FileSystemAccessRule("everyone", FileSystemRights.FullControl, AccessControlType.Allow);
                DirectorySecurity    ds   = new DirectorySecurity();
                ds.AddAccessRule(fsar);
                string requestDir     = textLocation.Text;
                string rootFolderName = textName.Text;
                string rootDir        = ODFileUtils.CombinePaths(requestDir, rootFolderName);
                //Enable file sharing for the A to Z folder.
                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    //Process.Start("net","usershare add OpenDentImages \""+rootDir+"\"");//for future use.
                }
                else                  //Windows
                {
                    Process.Start("NET", "SHARE OpenDentImages=\"" + rootDir + "\"");
                }
                //All folder names to be created should be put in this list, so that each folder is created exactly
                //the same way.
                string[] aToZFolderNames = new string[] {
                    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
                    "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
                    "EmailAttachments", "Forms", "Reports", "Sounds",
                };
                //Create A to Z folders in root folder.
                for (int i = 0; i < aToZFolderNames.Length; i++)
                {
                    string pathToCreate = ODFileUtils.CombinePaths(rootDir, aToZFolderNames[i]);
                    if (!Directory.Exists(pathToCreate))
                    {
                        // Mono does support Directory.CreateDirectory(string, DirectorySecurity)
#if !LINUX
                        Directory.CreateDirectory(pathToCreate, ds);
#else
                        Directory.CreateDirectory(pathToCreate);
#endif
                    }
                }
                //Save new image path into the DocPath and
                //set "use A to Z folders" check-box to checked.
                Prefs.UpdateString(PrefName.DocPath, rootDir);
                Prefs.UpdateString(PrefName.AtoZfolderNotRequired, "0");
                Cache.Refresh(InvalidType.Prefs);
                //Prefs_client.RefreshClient();
            }
            catch (Exception ex) {
                Logger.openlog.LogMB("Failed to create A to Z folders: " + ex.ToString(), Logger.Severity.ERROR);
            }
            DialogResult = DialogResult.OK;
        }
コード例 #5
0
ファイル: Helper.cs プロジェクト: dougericson/epg123
        public static bool CreateAndSetFolderAcl(string folder)
        {
            try
            {
                // establish security identifier for everyone and desired rights
                SecurityIdentifier Everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                FileSystemRights   Rights   = FileSystemRights.FullControl;

                // make sure directory exists
                DirectoryInfo Info       = new DirectoryInfo(folder);
                bool          newInstall = !Directory.Exists(folder);
                if (newInstall)
                {
                    Info = Directory.CreateDirectory(folder);
                }

                // check to make sure everyone does not already have access
                DirectorySecurity           Security           = Info.GetAccessControl(AccessControlSections.Access);
                AuthorizationRuleCollection AuthorizationRules = Security.GetAccessRules(true, true, typeof(NTAccount));
                foreach (FileSystemAccessRule rule in AuthorizationRules)
                {
                    if ((rule.IdentityReference.Value == Everyone.Translate(typeof(NTAccount)).ToString()) &&
                        (rule.AccessControlType == AccessControlType.Allow) &&
                        (rule.FileSystemRights == Rights))
                    {
                        return(true);
                    }
                }

                if (!newInstall && (DialogResult.OK != MessageBox.Show(string.Format("EPG123 is going to add the user 'Everyone' with Full Control rights to the \"{0}\" folder. This may take a while depending on how many files are in the folder and subfolders.", folder), "Edit Permissions", MessageBoxButtons.OK)))
                {
                    return(false);
                }

                // *** Add Access Rule to the actual directory itself
                FileSystemAccessRule AccessRule = new FileSystemAccessRule(Everyone,
                                                                           Rights,
                                                                           InheritanceFlags.None,
                                                                           PropagationFlags.NoPropagateInherit,
                                                                           AccessControlType.Allow);

                Security.ModifyAccessRule(AccessControlModification.Set, AccessRule, out bool Result);
                if (!Result)
                {
                    return(false);
                }

                // *** Always allow objects to inherit on a directory
                InheritanceFlags iFlags = InheritanceFlags.ObjectInherit;
                iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

                // *** Add Access rule for the inheritance
                AccessRule = new FileSystemAccessRule(Everyone,
                                                      Rights,
                                                      iFlags,
                                                      PropagationFlags.InheritOnly,
                                                      AccessControlType.Allow);
                Result = false;
                Security.ModifyAccessRule(AccessControlModification.Add, AccessRule, out Result);

                if (!Result)
                {
                    return(false);
                }

                Info.SetAccessControl(Security);
            }
            catch
            {
                if (!UserHasElevatedRights)
                {
                    MessageBox.Show(string.Format("EPG123 did not have sufficient priveleges to edit the folder \"{0}\" permissions. Please run this GUI with elevated rights (as Administrator) to make the necessary changes.", folder),
                                    "Folder Permissions Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                return(false);
            }
            return(true);
        }
コード例 #6
0
        /// <summary>
        /// ディレクトリアクセス権の比較
        /// </summary>
        /// <param name="src_dir">移管元ディレクトリ</param>
        /// <param name="dst_dir">移管先ディレクトリ</param>
        /// <param name="comparison_list">変換対象一覧</param>
        /// <returns></returns>
        private static bool directory_authority_comparative(DirectoryInfo src_dir, DirectoryInfo dst_dir, ref Dictionary <string, comparsion_unit> comparison_list)
        {
            try
            {
                DirectorySecurity src_dir_security = src_dir.GetAccessControl();    // 移管元のアクセス権取得
                DirectorySecurity dst_dir_security = dst_dir.GetAccessControl();    // 移管先のアクセス権取得
                Func <FileSystemAccessRule, bool> check_permission_of_dstdir = (FileSystemAccessRule comparative_auth) =>
                {
                    foreach (FileSystemAccessRule rule in dst_dir_security.GetAccessRules(true, true, typeof(NTAccount)))
                    {
                        if (!comparative_auth.IdentityReference.Equals(rule.IdentityReference))
                        {
                            continue;
                        }
                        if (!comparative_auth.FileSystemRights.Equals(rule.FileSystemRights))
                        {
                            continue;
                        }
                        if (!comparative_auth.InheritanceFlags.Equals(rule.InheritanceFlags))
                        {
                            continue;
                        }
                        if (!comparative_auth.PropagationFlags.Equals(rule.PropagationFlags))
                        {
                            continue;
                        }
                        if (!comparative_auth.AccessControlType.Equals(rule.AccessControlType))
                        {
                            continue;
                        }

                        return(true);
                    }

                    return(false);
                };

                if (src_dir_security.GetAccessRules(true, true, typeof(NTAccount)).Count <= 0)
                {
                    throw new Exception($"アクセス権の設定が無い src: {src_dir.FullName}");
                }

                if (dst_dir_security.GetAccessRules(true, true, typeof(NTAccount)).Count <= 0)
                {
                    throw new Exception($"アクセス権の設定が無い dst: {dst_dir.FullName}");
                }

                foreach (FileSystemAccessRule src_rule in src_dir_security.GetAccessRules(true, true, typeof(NTAccount)))
                {
                    int    cat_pint     = src_rule.IdentityReference.ToString().LastIndexOf('\\') + 1;
                    string account_name = src_rule.IdentityReference.ToString().Substring(cat_pint);

                    FileSystemAccessRule comparative_authority = src_rule;

                    if (comparison_list.ContainsKey(account_name)) // 変換対象か判定
                    {
                        comparsion_unit unit = comparison_list[account_name];
                        if (unit.del_flg == 1)
                        {
                            loger_manager.write_log($"削除対象アカウント: {unit.account_name} {unit.conversion_original} | {src_rule.FileSystemRights.ToString()}");
                            continue;
                        }

                        // アカウント名が変更後として比較対象変数に格納
                        comparative_authority = new FileSystemAccessRule(unit.after_conversion, src_rule.FileSystemRights, src_rule.InheritanceFlags, src_rule.PropagationFlags, src_rule.AccessControlType);
                    }

                    if (!check_permission_of_dstdir(comparative_authority)) // コピー先に権限があるか判定
                    {
                        loger_manager.write_log($"コピー元フォルダ名: {src_dir.FullName}\tコピー先フォルダ名: {dst_dir.FullName}\tアカウント名: {comparative_authority.IdentityReference}", "diff", "extracting");
                    }
                }

                return(true);
            }
            catch (Exception e)
            {
                loger_manager.write_log($"{e.GetType()} {e.Message}", "error");
                return(false);
            }
        }
コード例 #7
0
 public virtual bool RemoveAccessRule(FileSystemAccessRule rule)
 {
     return(_fileSystemSecurity.RemoveAccessRule(rule));
 }
コード例 #8
0
        /// <summary>
        /// Gets the application access rules implied by the access rights to the file.
        /// </summary>
        public static IList <ApplicationAccessRule> GetAccessRules(String filePath)
        {
            // get the current permissions from the file or directory.
            FileSystemSecurity security = null;

            FileInfo      fileInfo      = new FileInfo(filePath);
            DirectoryInfo directoryInfo = null;

            if (!fileInfo.Exists)
            {
                directoryInfo = new DirectoryInfo(filePath);

                if (!directoryInfo.Exists)
                {
                    throw new FileNotFoundException("File or directory does not exist.", filePath);
                }

                security = directoryInfo.GetAccessControl(AccessControlSections.Access);
            }
            else
            {
                security = fileInfo.GetAccessControl(AccessControlSections.Access);
            }

            // combine the access rules into a set of abstract application rules.
            List <ApplicationAccessRule> accessRules = new List <ApplicationAccessRule>();

            AuthorizationRuleCollection authorizationRules = security.GetAccessRules(true, true, typeof(NTAccount));

            for (int ii = 0; ii < authorizationRules.Count; ii++)
            {
                FileSystemAccessRule accessRule = authorizationRules[ii] as FileSystemAccessRule;

                // only care about file system rules.
                if (accessRule == null)
                {
                    continue;
                }

                ApplicationAccessRule rule = new ApplicationAccessRule();

                rule.RuleType     = ApplicationAccessRule.Convert(accessRule.AccessControlType);
                rule.IdentityName = accessRule.IdentityReference.Value;
                rule.Right        = ApplicationAccessRight.None;

                // create an allow rule.
                if (rule.RuleType == AccessControlType.Allow)
                {
                    // check if all rights required for configuration access exist.
                    if (((int)accessRule.FileSystemRights & (int)Configure) == (int)Configure)
                    {
                        rule.Right = ApplicationAccessRight.Configure;
                    }

                    // check if all rights required for update access exist.
                    else if (((int)accessRule.FileSystemRights & (int)Update) == (int)Update)
                    {
                        rule.Right = ApplicationAccessRight.Update;
                    }

                    // check if all rights required for read access exist.
                    else if (((int)accessRule.FileSystemRights & (int)Read) == (int)Read)
                    {
                        rule.Right = ApplicationAccessRight.Run;
                    }
                }

                // create a deny rule.
                else if (rule.RuleType == AccessControlType.Deny)
                {
                    // check if any rights required for read access are denied.
                    if (((int)accessRule.FileSystemRights & (int)Read) != 0)
                    {
                        rule.Right = ApplicationAccessRight.Run;
                    }

                    // check if any rights required for update access are denied.
                    else if (((int)accessRule.FileSystemRights & (int)Update) != 0)
                    {
                        rule.Right = ApplicationAccessRight.Update;
                    }

                    // check if any rights required for configure access are denied.
                    else if (((int)accessRule.FileSystemRights & (int)Configure) != 0)
                    {
                        rule.Right = ApplicationAccessRight.Configure;
                    }
                }

                // add rule if not trivial.
                if (rule.Right != ApplicationAccessRight.None)
                {
                    accessRules.Add(rule);
                }
            }

            return(accessRules);
        }
コード例 #9
0
 private void AddFileSystemAccessRule(DirectorySecurity permissions, FileSystemAccessRule accessRule)
 {
     permissions.AddAccessRule(accessRule);
 }
コード例 #10
0
ファイル: SetupWizard.cs プロジェクト: jjethwa/icinga2-1
        private void ConfigureService()
        {
            SetConfigureStatus(0, "Updating configuration files...");

            string output;

            string args = "";

            Invoke((MethodInvoker) delegate
            {
                string master_host, master_port;
                GetMasterHostPort(out master_host, out master_port);

                args += " --master_host " + master_host + "," + master_port;

                foreach (ListViewItem lvi in lvwEndpoints.Items)
                {
                    args += " --endpoint " + lvi.SubItems[0].Text.Trim();

                    if (lvi.SubItems.Count > 1)
                    {
                        args += "," + lvi.SubItems[1].Text.Trim() + "," + lvi.SubItems[2].Text.Trim();
                    }
                }
            });

            if (rdoListener.Checked)
            {
                args += " --listen ::," + txtListenerPort.Text.Trim();
            }

            if (chkAcceptConfig.Checked)
            {
                args += " --accept-config";
            }

            if (chkAcceptCommands.Checked)
            {
                args += " --accept-commands";
            }

            string ticket = txtTicket.Text.Trim();

            if (ticket.Length > 0)
            {
                args += " --ticket \"" + ticket + "\"";
            }

            args += " --trustedcert \"" + _TrustedFile + "\"";
            args += " --cn \"" + txtInstanceName.Text.Trim() + "\"";
            args += " --zone \"" + txtInstanceName.Text.Trim() + "\"";

            foreach (ListViewItem lvi in lvwGlobalZones.Items)
            {
                args += " --global_zones " + lvi.SubItems[0].Text.Trim();
            }

            if (chkDisableConf.Checked)
            {
                args += " --disable-confd";
            }

            if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
                            "node setup" + args,
                            out output))
            {
                ShowErrorText("Running command 'icinga2.exe " + "node setup" + args + "' produced the following output:\n" + output);
                return;
            }

            SetConfigureStatus(50, "Setting ACLs for the Icinga 2 directory...");

            string serviceUser = txtUser.Text.Trim();

            DirectoryInfo        di   = new DirectoryInfo(Program.Icinga2InstallDir);
            DirectorySecurity    ds   = di.GetAccessControl();
            FileSystemAccessRule rule = new FileSystemAccessRule(serviceUser,
                                                                 FileSystemRights.Modify,
                                                                 InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);

            try {
                ds.AddAccessRule(rule);
                di.SetAccessControl(ds);
            } catch (System.Security.Principal.IdentityNotMappedException) {
                ShowErrorText("Could not set ACLs for user \"" + serviceUser + "\". Identitiy is not mapped.\n");
                return;
            }

            SetConfigureStatus(75, "Installing the Icinga 2 service...");

            RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
                       "--scm-uninstall",
                       out output);

            if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
                            "daemon --validate",
                            out output))
            {
                ShowErrorText("Running command 'icinga2.exe daemon --validate' produced the following output:\n" + output);
                return;
            }

            if (!RunProcess(Program.Icinga2InstallDir + "\\sbin\\icinga2.exe",
                            "--scm-install --scm-user \"" + serviceUser + "\" daemon",
                            out output))
            {
                ShowErrorText("\nRunning command 'icinga2.exe --scm-install --scm-user \"" +
                              serviceUser + "\" daemon' produced the following output:\n" + output);
                return;
            }

            if (chkInstallNSCP.Checked)
            {
                SetConfigureStatus(85, "Waiting for NSClient++ installation to complete...");

                Process proc = new Process();
                proc.StartInfo.FileName  = "msiexec.exe";
                proc.StartInfo.Arguments = "/i \"" + Program.Icinga2InstallDir + "\\sbin\\NSCP.msi\"";
                proc.Start();
                proc.WaitForExit();
            }

            SetConfigureStatus(100, "Finished.");

            // Override the completed text
            lblSetupCompleted.Text = "The Icinga 2 Windows client was set up successfully.";

            // Add a note for the user for ticket-less signing
            if (ticket.Length == 0)
            {
                lblSetupCompleted.Text += "\n\nTicket was not specified. Please sign the certificate request on the Icinga 2 master node (requires v2.8+).";
            }

            FinishConfigure();
        }
コード例 #11
0
        /// <summary>
        /// Gets the application access rules implied by the access rights to the file.
        /// </summary>
        public static void SetAccessRules(String filePath, IList <ApplicationAccessRule> accessRules, bool replaceExisting)
        {
            // get the current permissions from the file or directory.
            FileSystemSecurity security = null;

            FileInfo      fileInfo      = new FileInfo(filePath);
            DirectoryInfo directoryInfo = null;

            if (!fileInfo.Exists)
            {
                directoryInfo = new DirectoryInfo(filePath);

                if (!directoryInfo.Exists)
                {
                    throw new FileNotFoundException("File or directory does not exist.", filePath);
                }

                security = directoryInfo.GetAccessControl(AccessControlSections.Access);
            }
            else
            {
                security = fileInfo.GetAccessControl(AccessControlSections.Access);
            }

            if (replaceExisting)
            {
                // can't use inhieritance when setting permissions
                security.SetAccessRuleProtection(true, false);

                // remove all existing access rules.
                AuthorizationRuleCollection authorizationRules = security.GetAccessRules(true, true, typeof(NTAccount));

                for (int ii = 0; ii < authorizationRules.Count; ii++)
                {
                    FileSystemAccessRule accessRule = authorizationRules[ii] as FileSystemAccessRule;

                    // only care about file system rules.
                    if (accessRule == null)
                    {
                        continue;
                    }

                    security.RemoveAccessRule(accessRule);
                }
            }

            // allow children to inherit rules for directories.
            InheritanceFlags flags = InheritanceFlags.None;

            if (directoryInfo != null)
            {
                flags = InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit;
            }

            // add the new rules.
            for (int ii = 0; ii < accessRules.Count; ii++)
            {
                ApplicationAccessRule applicationRule = accessRules[ii];

                IdentityReference identityReference = applicationRule.IdentityReference;

                if (identityReference == null)
                {
                    if (applicationRule.IdentityName.StartsWith("S-"))
                    {
                        SecurityIdentifier sid = new SecurityIdentifier(applicationRule.IdentityName);

                        if (!sid.IsValidTargetType(typeof(NTAccount)))
                        {
                            continue;
                        }

                        identityReference = sid.Translate(typeof(NTAccount));
                    }
                    else
                    {
                        identityReference = new NTAccount(applicationRule.IdentityName);
                    }
                }

                FileSystemAccessRule fileRule = null;

                switch (applicationRule.Right)
                {
                case ApplicationAccessRight.Run:
                {
                    fileRule = new FileSystemAccessRule(
                        identityReference,
                        (applicationRule.RuleType == AccessControlType.Allow) ? Read : Configure,
                        flags,
                        PropagationFlags.None,
                        ApplicationAccessRule.Convert(applicationRule.RuleType));

                    break;
                }

                case ApplicationAccessRight.Update:
                {
                    fileRule = new FileSystemAccessRule(
                        identityReference,
                        (applicationRule.RuleType == AccessControlType.Allow) ? Update : ConfigureOnly | UpdateOnly,
                        flags,
                        PropagationFlags.None,
                        ApplicationAccessRule.Convert(applicationRule.RuleType));

                    security.SetAccessRule(fileRule);
                    break;
                }

                case ApplicationAccessRight.Configure:
                {
                    fileRule = new FileSystemAccessRule(
                        identityReference,
                        (applicationRule.RuleType == AccessControlType.Allow) ? Configure : ConfigureOnly,
                        flags,
                        PropagationFlags.None,
                        ApplicationAccessRule.Convert(applicationRule.RuleType));

                    break;
                }
                }

                try
                {
                    security.SetAccessRule(fileRule);
                }
                catch (Exception e)
                {
                    Utils.Trace(
                        "Could not set access rule for account '{0}' on file '{1}'. Error={2}",
                        applicationRule.IdentityName,
                        filePath,
                        e.Message);
                }
            }

            if (directoryInfo != null)
            {
                directoryInfo.SetAccessControl((DirectorySecurity)security);
                return;
            }

            fileInfo.SetAccessControl((FileSecurity)security);
        }
コード例 #12
0
        public static void Start(uint sessionId, string arguments)
        {
            lock (lockObject)
            {
                restart_count        = 0;
                MpegStream.sessionId = sessionId;
                if (sessionId < 1)
                {
                    throw new Exception("sessionId == " + sessionId);
                }

                //if (string.IsNullOrWhiteSpace(Settings.General.CapturedMonitorDeviceName))
                //{
                //    Settings.General.CapturedMonitorDeviceName = MonitorRoutines.GetDefaultMonitorName();
                //    if (string.IsNullOrWhiteSpace(Settings.General.CapturedMonitorDeviceName))
                //        throw new Exception("No monitor was found.");
                //}
                //WinApi.User32.RECT? an = MonitorRoutines.GetMonitorAreaByMonitorName(Settings.General.CapturedMonitorDeviceName);
                //if (an == null)
                //{
                //    string defaultMonitorName = MonitorRoutines.GetDefaultMonitorName();
                //    Log.Main.Warning("Monitor '" + Settings.General.CapturedMonitorDeviceName + "' was not found. Using default one '" + defaultMonitorName + "'");
                //    Settings.General.CapturedMonitorDeviceName = defaultMonitorName;
                //    an = MonitorRoutines.GetMonitorAreaByMonitorName(Settings.General.CapturedMonitorDeviceName);
                //    if (an == null)
                //        throw new Exception("Monitor '" + Settings.General.CapturedMonitorDeviceName + "' was not found.");
                //}
                string source;
                if (Settings.General.CapturedMonitorDeviceName == null || Settings.General.CapturedMonitorDeviceName == Settings.GeneralSettings.CapturedMonitorDeviceName_ALL_DISPLAYS)
                {
                    source = " -i desktop ";
                }
                else
                {
                    if (Settings.General.CapturedMonitorRectangle == null)
                    {
                        Log.Main.Inform("CapturedMonitorRectangle is empty. Running " + userSessionAgent);
                        UserSessionApi.OpenApi();
                        WinApi.Advapi32.CreationFlags cfs = 0;
                        cfs |= WinApi.Advapi32.CreationFlags.CREATE_NO_WINDOW;
                        string  cl  = "\"" + Log.AppDir + "\\" + userSessionAgent + "\"";
                        uint    pid = ProcessRoutines.CreateProcessAsUserOfCurrentProcess(sessionId, cl, cfs);
                        Process p   = Process.GetProcessById((int)pid);
                        if (p != null && !p.HasExited)
                        {
                            p.WaitForExit();
                        }
                        UserSessionApi.CloseApi();
                        Settings.General.Reload();
                        if (Settings.General.CapturedMonitorRectangle == null)
                        {
                            throw new Exception("Could not get rectangle for monitor '" + Settings.General.CapturedMonitorDeviceName + "'");
                        }
                        //if (Settings.General.CapturedMonitorRectangle == null)
                        //    throw new Exception("Could not get rectangle for monitor '" + Settings.General.CapturedMonitorDeviceName + "'. Properly edit and save monitor setting in the systray menu.");
                    }
                    WinApi.User32.RECT a = (WinApi.User32.RECT)Settings.General.CapturedMonitorRectangle;
                    source = " -offset_x " + a.Left + " -offset_y " + a.Top + " -video_size " + (a.Right - a.Left) + "x" + (a.Bottom - a.Top) + " -show_region 1 -i desktop ";
                }

                arguments   = Regex.Replace(arguments, @"-framerate\s+\d+", "$0" + source);
                commandLine = "\"" + Log.AppDir + "\\ffmpeg.exe\" " + arguments;

                dwCreationFlags = 0;
                if (!Settings.General.ShowMpegWindow)
                {
                    dwCreationFlags |= WinApi.Advapi32.CreationFlags.CREATE_NO_WINDOW;
                    //startupInfo.dwFlags |= Win32Process.STARTF_USESTDHANDLES;
                    //startupInfo.wShowWindow = Win32Process.SW_HIDE;
                }

                if (Settings.General.WriteMpegOutput2Log)
                {
                    string file0 = Log.WorkDir + "\\ffmpeg_" + DateTime.Now.ToString("yyMMddHHmmss");
                    string file  = file0;
                    for (int count = 1; File.Exists(file); count++)
                    {
                        file = file0 + "_" + count.ToString();
                    }
                    file += ".log";

                    File.WriteAllText(file, @"STARTED AT " + DateTime.Now.ToString() + @":
>" + commandLine + @"

", Encoding.UTF8);
                    FileSecurity         fileSecurity         = File.GetAccessControl(file);
                    FileSystemAccessRule fileSystemAccessRule = new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.AppendData, AccessControlType.Allow);
                    fileSecurity.AddAccessRule(fileSystemAccessRule);
                    File.SetAccessControl(file, fileSecurity);

                    commandLine = Environment.SystemDirectory + "\\cmd.exe /c \"" + commandLine + " 1>>\"" + file + "\",2>&1\"";
                }

                start();
            }
        }
コード例 #13
0
        public void ApplyConfigChange()
        {
            var accountName = string.Equals(ServiceAccount, "LocalSystem", StringComparison.OrdinalIgnoreCase) ? "System" : ServiceAccount;
            var oldSettings = InstanceFinder.FindServiceControlInstance(Name);

            var fileSystemChanged = !string.Equals(oldSettings.LogPath, LogPath, StringComparison.OrdinalIgnoreCase);

            var queueNamesChanged = !(string.Equals(oldSettings.AuditQueue, AuditQueue, StringComparison.OrdinalIgnoreCase) &&
                                      string.Equals(oldSettings.ErrorQueue, ErrorQueue, StringComparison.OrdinalIgnoreCase) &&
                                      string.Equals(oldSettings.AuditLogQueue, AuditLogQueue, StringComparison.OrdinalIgnoreCase) &&
                                      string.Equals(oldSettings.ErrorLogQueue, ErrorLogQueue, StringComparison.OrdinalIgnoreCase) &&
                                      oldSettings.ForwardErrorMessages == ForwardErrorMessages &&
                                      oldSettings.ForwardAuditMessages == ForwardAuditMessages
                                      );


            RecreateUrlAcl(oldSettings);

            if (fileSystemChanged)
            {
                var account          = new NTAccount(accountName);
                var modifyAccessRule = new FileSystemAccessRule(account, FileSystemRights.Modify | FileSystemRights.Traverse | FileSystemRights.ListDirectory, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
                FileUtils.CreateDirectoryAndSetAcl(LogPath, modifyAccessRule);
            }

            Service.Description = Description;

            var configuration = ConfigurationManager.OpenExeConfiguration(Service.ExePath);
            var settings      = configuration.AppSettings.Settings;
            var version       = Version;

            settings.Set(SettingsList.HostName, HostName);
            settings.Set(SettingsList.Port, Port.ToString());
            settings.Set(SettingsList.DatabaseMaintenancePort, DatabaseMaintenancePort.ToString(), version);
            settings.Set(SettingsList.LogPath, LogPath);
            settings.Set(SettingsList.ForwardAuditMessages, ForwardAuditMessages.ToString());
            settings.Set(SettingsList.ForwardErrorMessages, ForwardErrorMessages.ToString(), version);
            settings.Set(SettingsList.AuditRetentionPeriod, AuditRetentionPeriod.ToString(), version);
            settings.Set(SettingsList.ErrorRetentionPeriod, ErrorRetentionPeriod.ToString(), version);

            settings.RemoveIfRetired(SettingsList.HoursToKeepMessagesBeforeExpiring, version);

            settings.Set(SettingsList.AuditQueue, AuditQueue);
            settings.Set(SettingsList.ErrorQueue, ErrorQueue);

            if (Version >= Compatibility.ForwardingQueuesAreOptional.SupportedFrom)
            {
                if (!ForwardErrorMessages)
                {
                    ErrorLogQueue = null;
                }

                if (!ForwardAuditMessages)
                {
                    AuditLogQueue = null;
                }
            }

            settings.Set(SettingsList.ErrorLogQueue, ErrorLogQueue);
            settings.Set(SettingsList.AuditLogQueue, AuditLogQueue);

            configuration.ConnectionStrings.ConnectionStrings.Set("NServiceBus/Transport", ConnectionString);
            configuration.Save();

            var passwordSet             = !string.IsNullOrWhiteSpace(ServiceAccountPwd);
            var accountChanged          = !string.Equals(oldSettings.ServiceAccount, ServiceAccount, StringComparison.OrdinalIgnoreCase);
            var connectionStringChanged = !string.Equals(ConnectionString, oldSettings.ConnectionString, StringComparison.Ordinal);

            //have to save config prior to creating queues (if needed)

            if (queueNamesChanged || accountChanged || connectionStringChanged)
            {
                try
                {
                    QueueCreation.RunQueueCreation(this);
                }
                catch (QueueCreationFailedException ex)
                {
                    ReportCard.Errors.Add(ex.Message);
                }
                catch (QueueCreationTimeoutException ex)
                {
                    ReportCard.Errors.Add(ex.Message);
                }
            }

            if (passwordSet || accountChanged)
            {
                Service.ChangeAccountDetails(accountName, ServiceAccountPwd);
            }
        }
コード例 #14
0
        /// <summary>
        /// ファイルアクセス権の比較
        /// </summary>
        /// <param name="src_file">移管元ファイル名</param>
        /// <param name="dst_file">移管先ファイル</param>
        /// <param name="comparison_list">変換対象一覧</param>
        /// <returns></returns>
        private static bool file_permission_comparative(FileInfo src_file, FileInfo dst_file, ref Dictionary <string, comparsion_unit> comparison_list)
        {
            try
            {
                FileSecurity src_file_security = src_file.GetAccessControl();   // 移管元のアクセス権取得
                FileSecurity dst_file_security = dst_file.GetAccessControl();   // 移管先のアクセス権取得
                Func <FileSystemAccessRule, bool> check_permission_of_dstfile = (FileSystemAccessRule comparative_auth) =>
                {
                    foreach (FileSystemAccessRule rule in dst_file_security.GetAccessRules(true, true, typeof(NTAccount)))
                    {
                        // 下記の何れかが異なれば trueを返さない
                        if (!comparative_auth.IdentityReference.Equals(rule.IdentityReference))
                        {
                            continue;
                        }
                        if (!comparative_auth.FileSystemRights.Equals(rule.FileSystemRights))
                        {
                            continue;
                        }
                        if (!comparative_auth.InheritanceFlags.Equals(rule.InheritanceFlags))
                        {
                            continue;
                        }
                        if (!comparative_auth.PropagationFlags.Equals(rule.PropagationFlags))
                        {
                            continue;
                        }
                        if (!comparative_auth.AccessControlType.Equals(rule.AccessControlType))
                        {
                            continue;
                        }

                        return(true);
                    }

                    return(false);
                };

                if (src_file_security.GetAccessRules(true, true, typeof(NTAccount)).Count <= 0)
                {
                    throw new Exception($"アクセス権の設定が無い src: {src_file.FullName}");
                }

                if (dst_file_security.GetAccessRules(true, true, typeof(NTAccount)).Count <= 0)
                {
                    throw new Exception($"アクセス権の設定が無い dst: {dst_file.FullName}");
                }

                foreach (FileSystemAccessRule src_rule in src_file_security.GetAccessRules(true, true, typeof(NTAccount)))
                {
                    int    cat_pint     = src_rule.IdentityReference.ToString().LastIndexOf('\\') + 1;
                    string account_name = src_rule.IdentityReference.ToString().Substring(cat_pint);

                    FileSystemAccessRule comparative_authority = src_rule;

                    if (comparison_list.ContainsKey(account_name))
                    {
                        loger_manager.write_log($"適応先: {dst_file.FullName} " + ((src_rule.InheritanceFlags & InheritanceFlags.ContainerInherit) > 0 ? "このフォルダとサブフォルダ" : "このフォルダのみ"), "conversion");

                        comparsion_unit unit = comparison_list[account_name];
                        if (unit.del_flg == 1)
                        {
                            loger_manager.write_log($"削除対象アカウント: {unit.account_name} {unit.conversion_original} | {src_rule.FileSystemRights.ToString()}", "del account");
                            continue; // del_flgが1のものは権限設定処理を行わない
                        }

                        // アカウント名が変更後として比較対象変数に格納
                        comparative_authority = new FileSystemAccessRule(unit.after_conversion, src_rule.FileSystemRights, src_rule.InheritanceFlags, src_rule.PropagationFlags, src_rule.AccessControlType);
                    }

                    if (!check_permission_of_dstfile(comparative_authority)) // コピー先に権限があるか判定
                    {
                        loger_manager.write_log($"コピー元ファイル名: {src_file.FullName}\tコピー先ファイル名: {dst_file.FullName}\tアカウント名: {comparative_authority.IdentityReference}", "diff", "extracting");
                    }
                }

                return(true);
            }
            catch (Exception e)
            {
                loger_manager.write_log(e.Message, "error");
                return(false);
            }
        }
コード例 #15
0
 public bool RemoveAccessRule(FileSystemAccessRule rule);
コード例 #16
0
 public void AddAccessRule(FileSystemAccessRule rule)
 {
 }
コード例 #17
0
 public void RemoveAccessRuleSpecific(FileSystemAccessRule rule);
コード例 #18
0
 public void ResetAccessRule(FileSystemAccessRule rule)
 {
 }
コード例 #19
0
 public virtual void ResetAccessRule(FileSystemAccessRule rule)
 {
     _fileSystemSecurity.ResetAccessRule(rule);
 }
コード例 #20
0
 public bool RemoveAccessRule(FileSystemAccessRule rule)
 {
 }
コード例 #21
0
 public virtual void RemoveAccessRuleSpecific(FileSystemAccessRule rule)
 {
     _fileSystemSecurity.RemoveAccessRuleSpecific(rule);
 }
コード例 #22
0
 public void RemoveAccessRuleAll(FileSystemAccessRule rule)
 {
 }
コード例 #23
0
 private static bool IsRightSetinAccessRule(FileSystemAccessRule accessrule, FileSystemRights right)
 {
     return((accessrule.FileSystemRights & right) == right);
 }
コード例 #24
0
 public void RemoveAccessRuleSpecific(FileSystemAccessRule rule)
 {
 }
コード例 #25
0
        /// <summary>
        /// Returs the if <paramref name="right"/> is in <sparamref name="rule"/>
        /// </summary>
        public Boolean Contains(FileSystemRights right, FileSystemAccessRule rule)
        {
            Contract.Requires(rule != null);

            return((( Int32 )right & ( Int32 )rule.FileSystemRights) == ( Int32 )right);
        }
コード例 #26
0
ファイル: SitePool.cs プロジェクト: Rhayar-dr/kudu-1
        private static async Task <ApplicationManager> CreateApplicationInternal(int siteIndex)
        {
            string applicationName = _sitePrefix + siteIndex;

            string operationName = "SitePool.CreateApplicationInternal " + applicationName;

            var context     = new KuduTestContext();
            var siteManager = GetSiteManager(context);

            Site site = siteManager.GetSite(applicationName);

            if (site != null)
            {
                TestTracer.Trace("{0} Site already exists at {1}. Reusing site", operationName, site.SiteUrl);

                TestTracer.Trace("{0} Reset existing site content", operationName);
                await siteManager.ResetSiteContent(applicationName);

                RunAgainstCustomKuduUrlIfRequired(site);

                var appManager = new ApplicationManager(siteManager, site, applicationName)
                {
                    SitePoolIndex = siteIndex
                };

                // Make sure we start with the correct default file as some tests expect it
                WriteIndexHtml(appManager);

                TestTracer.Trace("{0} completed", operationName);
                return(appManager);
            }
            else
            {
                TestTracer.Trace("{0} Creating new site", operationName);
                lock (_createSiteLock)
                {
                    if (ConfigurationManager.AppSettings["UseNetworkServiceIdentity"] == "true")
                    {
                        var applicationsPath = context.Configuration.ApplicationsPath;
                        if (!Directory.Exists(applicationsPath))
                        {
                            Directory.CreateDirectory(applicationsPath);

                            var accessRule = new FileSystemAccessRule("NETWORK SERVICE",
                                                                      fileSystemRights: FileSystemRights.Modify | FileSystemRights.Write | FileSystemRights.ReadAndExecute | FileSystemRights.Read | FileSystemRights.ListDirectory,
                                                                      inheritanceFlags: InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                                      propagationFlags: PropagationFlags.None,
                                                                      type: AccessControlType.Allow);

                            var directoryInfo = new DirectoryInfo(applicationsPath);
                            DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
                            directorySecurity.AddAccessRule(accessRule);
                            directoryInfo.SetAccessControl(directorySecurity);
                        }
                    }

                    site = siteManager.CreateSiteAsync(applicationName).Result;

                    RunAgainstCustomKuduUrlIfRequired(site);
                }

                TestTracer.Trace("{0} Created new site at {1}", operationName, site.SiteUrl);
                return(new ApplicationManager(siteManager, site, applicationName)
                {
                    SitePoolIndex = siteIndex
                });
            }
        }
コード例 #27
0
ファイル: Program.cs プロジェクト: DoctorVanGogh/UtinyRipper
        private static void CheckWritePermission(string path)
        {
            WindowsIdentity  identity           = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal          = new WindowsPrincipal(identity);
            bool             isInRoleWithAccess = false;

            try
            {
                DirectoryInfo               di    = new DirectoryInfo(path);
                DirectorySecurity           ds    = di.GetAccessControl();
                AuthorizationRuleCollection rules = ds.GetAccessRules(true, true, typeof(NTAccount));

                foreach (AuthorizationRule rule in rules)
                {
                    FileSystemAccessRule fsAccessRule = rule as FileSystemAccessRule;
                    if (fsAccessRule == null)
                    {
                        continue;
                    }

                    if ((fsAccessRule.FileSystemRights & FileSystemRights.Write) != 0)
                    {
                        NTAccount ntAccount = rule.IdentityReference as NTAccount;
                        if (ntAccount == null)
                        {
                            continue;
                        }

                        if (principal.IsInRole(ntAccount.Value))
                        {
                            if (fsAccessRule.AccessControlType == AccessControlType.Deny)
                            {
                                isInRoleWithAccess = false;
                                break;
                            }
                            isInRoleWithAccess = true;
                        }
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
            }

            if (!isInRoleWithAccess)
            {
                // is run as administrator?
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    return;
                }

                // try run as admin
                Process  proc = new Process();
                string[] args = Environment.GetCommandLineArgs();
                proc.StartInfo.FileName        = args[0];
                proc.StartInfo.Arguments       = string.Join(" ", args.Skip(1).Select(t => $"\"{t}\""));
                proc.StartInfo.UseShellExecute = true;
                proc.StartInfo.Verb            = "runas";

                try
                {
                    proc.Start();
                    Environment.Exit(0);
                }
                catch (Win32Exception ex)
                {
                    //The operation was canceled by the user.
                    const int ERROR_CANCELLED = 1223;
                    if (ex.NativeErrorCode == ERROR_CANCELLED)
                    {
                        Logger.Instance.Log(LogType.Error, LogCategory.General, $"You can't export to folder {path} without Administrator permission");
                        Console.ReadKey();
                    }
                    else
                    {
                        Logger.Instance.Log(LogType.Error, LogCategory.General, $"You have to restart application as Administator in order to export to folder {path}");
                        Console.ReadKey();
                    }
                }
            }
        }
コード例 #28
0
        /// <summary>
        /// Set specified rights to the file or directory.
        /// </summary>
        /// <param name="path">The path to a file or directory.</param>
        /// <param name="rights">Rights to check.</param>
        /// <param name="sid">User to check.</param>
        /// <param name="inheritance">Inheritance options.</param>
        /// <param name="propagation">Propagation options.</param>
        /// <returns>True if success, False if failed to set the rights.</returns>
        public static bool SetRights(
            string path,
            FileSystemRights rights,
            SecurityIdentifier sid,
            // Applies to directories and sub directories by default.
            InheritanceFlags?inheritance = null,
            PropagationFlags?propagation = null)
        {
            if (string.IsNullOrEmpty(path))
            {
                return(false);
            }
            if (sid == null)
            {
                return(false);
            }
            if (!File.Exists(path) && !Directory.Exists(path))
            {
                return(false);
            }
            var attributes  = File.GetAttributes(path);
            var isDirectory = attributes.HasFlag(FileAttributes.Directory);
            var security    = isDirectory
                                ? (FileSystemSecurity)Directory.GetAccessControl(path)
                                : (FileSystemSecurity)File.GetAccessControl(path);
            FileSystemAccessRule sidRule = null;
            // Do not include inherited permissions, because.
            var rules = security.GetAccessRules(true, false, sid.GetType());

            foreach (FileSystemAccessRule rule in rules)
            {
                if (rule.IdentityReference != sid)
                {
                    continue;
                }
                if (rule.AccessControlType == AccessControlType.Allow)
                {
                    sidRule = rule;
                    break;
                }
            }
            if (sidRule == null)
            {
                sidRule = new FileSystemAccessRule(
                    sid,
                    // Set new permissions.
                    rights,
                    inheritance ?? (
                        isDirectory
                                                        ? InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit
                                                        : InheritanceFlags.None
                        ),
                    propagation ?? PropagationFlags.None,
                    AccessControlType.Allow
                    );
                security.AddAccessRule(sidRule);
            }
            else
            {
                var newRule = new FileSystemAccessRule(
                    sid,
                    // Append missing permissions.
                    sidRule.FileSystemRights | rights,
                    inheritance ?? sidRule.InheritanceFlags,
                    propagation ?? sidRule.PropagationFlags,
                    AccessControlType.Allow
                    );
                security.SetAccessRule(newRule);
            }
            if (isDirectory)
            {
                Directory.SetAccessControl(path, (DirectorySecurity)security);
            }
            else
            {
                File.SetAccessControl(path, (FileSecurity)security);
            }
            return(true);
        }
コード例 #29
0
 private bool GetAccessStatus(FileSystemRights mode, FileSystemAccessRule rule)
 {
     return ((mode & rule.FileSystemRights) == mode ? true : false);
 }
コード例 #30
0
        public void InheritedPermissions()
        {
            AuthorizationRuleCollection rules;
            DirectorySecurity           dirSecurity; FileSecurity fileSecurity;
            SecurityIdentifier          usersSid            = new SecurityIdentifier("BU");
            SecurityIdentifier          worldSid            = new SecurityIdentifier("WD");
            FileSystemAccessRule        worldDirFullControl = new FileSystemAccessRule
                                                                  (worldSid, FileSystemRights.FullControl,
                                                                  InheritanceFlags.ObjectInherit, PropagationFlags.None,
                                                                  AccessControlType.Allow);

            if (PlatformID.Win32NT != Environment.OSVersion.Platform)
            {
                Assert.Ignore();
            }

            string        dirpath  = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            string        dirpath2 = null;
            string        filepath = null;
            DirectoryInfo dirinfo  = Directory.CreateDirectory(dirpath);

            try {
                // Set Full Control to Everyone.
                dirSecurity = dirinfo.GetAccessControl();
                dirSecurity.SetGroup(usersSid);
                dirSecurity.AddAccessRule(worldDirFullControl);
                Directory.SetAccessControl(dirpath, dirSecurity);

                // Did the rule store on the directory?
                dirSecurity = Directory.GetAccessControl(dirpath);
                rules       = dirSecurity.GetAccessRules(true, false, typeof(SecurityIdentifier));
                Assert.AreEqual(usersSid, dirSecurity.GetGroup(typeof(SecurityIdentifier)));
                Assert.AreEqual(1, rules.Count);
                Assert.AreEqual(worldSid, rules[0].IdentityReference);
                Assert.AreEqual(InheritanceFlags.ObjectInherit, rules[0].InheritanceFlags);
                Assert.AreEqual(PropagationFlags.None, rules[0].PropagationFlags);
                Assert.IsFalse(rules[0].IsInherited);

                // Create a file. It will have no explicit rules.
                filepath = Path.Combine(dirpath, Path.GetRandomFileName());
                using (FileStream file = new FileStream(filepath, FileMode.Create, FileAccess.ReadWrite)) {
                    fileSecurity = file.GetAccessControl();

                    rules = fileSecurity.GetAccessRules(true, false, typeof(SecurityIdentifier));
                    Assert.AreEqual(0, rules.Count);
                }

                // Make sure the file has inherited the Full Control access rule.
                FileInfo fileInfo = new FileInfo(filepath);
                fileSecurity = fileInfo.GetAccessControl();

                rules = fileSecurity.GetAccessRules(false, true, typeof(SecurityIdentifier));
                bool fileInheritedRule = false;
                foreach (FileSystemAccessRule rule in rules)
                {
                    if (rule.AccessControlType == AccessControlType.Allow &&
                        rule.FileSystemRights == FileSystemRights.FullControl &&
                        rule.IdentityReference == worldSid &&
                        rule.IsInherited &&
                        rule.InheritanceFlags == InheritanceFlags.None &&
                        rule.PropagationFlags == PropagationFlags.None)                     // only containers get non-None flags
                    {
                        fileInheritedRule = true;
                    }
                }
                Assert.IsTrue(fileInheritedRule);

                // ContainerInherit not being set, create a directory.
                // Its inherited rule will have propagation flags to indicate only its children are affected.
                dirpath2    = Path.Combine(dirpath, Path.GetRandomFileName());
                dirinfo     = Directory.CreateDirectory(dirpath2);
                dirSecurity = dirinfo.GetAccessControl();

                rules = dirSecurity.GetAccessRules(false, true, typeof(SecurityIdentifier));
                bool dirInheritedRule = false;
                foreach (FileSystemAccessRule rule in rules)
                {
                    if (rule.AccessControlType == AccessControlType.Allow &&
                        rule.FileSystemRights == FileSystemRights.FullControl &&
                        rule.IdentityReference == worldSid &&
                        rule.IsInherited &&
                        rule.InheritanceFlags == InheritanceFlags.ObjectInherit &&
                        rule.PropagationFlags == PropagationFlags.InheritOnly)                     // <-- key difference
                    {
                        dirInheritedRule = true;
                    }
                }
                Assert.IsTrue(dirInheritedRule);
            } finally {
                if (null != filepath)
                {
                    File.Delete(filepath);
                }
                if (null != dirpath2)
                {
                    Directory.Delete(dirpath2);
                }
                Directory.Delete(dirpath);
            }
        }
コード例 #31
0
 public void AddAccessRule(FileSystemAccessRule rule);
コード例 #32
0
        private async Task SetInstallationDataPath(MCProfile p, BLInstallation i)
        {
            await Task.Run(() =>
            {
                try
                {
                    string LocalStateFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Packages", MINECRAFT_PACKAGE_FAMILY, "LocalState");
                    string PackageFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Packages", MINECRAFT_PACKAGE_FAMILY, "LocalState", "games", "com.mojang");
                    string PackageBakFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Packages", MINECRAFT_PACKAGE_FAMILY, "LocalState", "games", "com.mojang.default");
                    string ProfileFolder = Path.GetFullPath(LauncherModel.Default.FilepathManager.GetInstallationsFolderPath(p.Name, i.DirectoryName_Full));

                    if (Directory.Exists(PackageFolder))
                    {
                        var dir = new DirectoryInfo(PackageFolder);
                        if (!dir.IsSymbolicLink()) dir.MoveTo(PackageBakFolder);
                        else dir.Delete(true);
                    }

                    DirectoryInfo profileDir = Directory.CreateDirectory(ProfileFolder);
                    SymLinkHelper.CreateSymbolicLink(PackageFolder, ProfileFolder, SymLinkHelper.SymbolicLinkType.Directory);
                    DirectoryInfo pkgDir = Directory.CreateDirectory(PackageFolder);
                    DirectoryInfo lsDir = Directory.CreateDirectory(LocalStateFolder);

                    SecurityIdentifier owner = WindowsIdentity.GetCurrent().User;
                    SecurityIdentifier authenticated_users_identity = new SecurityIdentifier("S-1-5-11");

                    FileSystemAccessRule owner_access_rules = new FileSystemAccessRule(owner, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);
                    FileSystemAccessRule au_access_rules = new FileSystemAccessRule(authenticated_users_identity, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);

                    var lsSecurity = lsDir.GetAccessControl();
                    AuthorizationRuleCollection rules = lsSecurity.GetAccessRules(true, true, typeof(NTAccount));
                    List<FileSystemAccessRule> needed_rules = new List<FileSystemAccessRule>();
                    foreach (AccessRule rule in rules)
                    {
                        if (rule.IdentityReference is SecurityIdentifier)
                        {
                            var required_rule = new FileSystemAccessRule(rule.IdentityReference, FileSystemRights.FullControl, rule.InheritanceFlags, rule.PropagationFlags, rule.AccessControlType);
                            needed_rules.Add(required_rule);
                        }
                    }

                    var pkgSecurity = pkgDir.GetAccessControl();
                    pkgSecurity.SetOwner(owner);
                    pkgSecurity.AddAccessRule(au_access_rules);
                    pkgSecurity.AddAccessRule(owner_access_rules);
                    pkgDir.SetAccessControl(pkgSecurity);

                    var profileSecurity = profileDir.GetAccessControl();
                    profileSecurity.SetOwner(owner);
                    profileSecurity.AddAccessRule(au_access_rules);
                    profileSecurity.AddAccessRule(owner_access_rules);
                    needed_rules.ForEach(x => profileSecurity.AddAccessRule(x));
                    profileDir.SetAccessControl(profileSecurity);
                }
                catch (Exception e)
                {
                    ErrorScreenShow.exceptionmsg(e);
                    throw e;
                }
            });
            Thread.Sleep(1000);
        }
コード例 #33
0
 public void RemoveAccessRuleAll(FileSystemAccessRule rule);
コード例 #34
0
 public virtual void AddAccessRule(FileSystemAccessRule rule)
 {
     _fileSystemSecurity.AddAccessRule(rule);
 }
コード例 #35
0
 public void SetAccessRule(FileSystemAccessRule rule);
コード例 #36
0
        /// <summary>
        /// Checks that a directory can be read by the current process
        /// </summary>
        /// <param name="directoryName"></param>
        /// <returns></returns>
        public static bool CheckReadAccess(DirectoryInfo directory, List <string> diagnostics = null)
        {
            if (!directory.Exists)
            {
                return(false);
            }

            System.Security.Principal.WindowsIdentity  user      = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new WindowsPrincipal(user);

            // Get the collection of authorization rules that apply to the current directory
            AuthorizationRuleCollection acl = directory.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));

            if (diagnostics != null)
            {
                diagnostics.Add("Checking process group membership...");
                foreach (IdentityReference idref in user.Groups)
                {
                    diagnostics.Add("- " + SidToAccountName(idref));
                }
                diagnostics.Add("Now testing access rules...");
            }
            // These are set to true if either the allow read or deny read access rights are set
            bool allowRead = false;
            bool denyRead  = false;

            for (int x = 0; x < acl.Count; x++)
            {
                FileSystemAccessRule currentRule = (FileSystemAccessRule)acl[x];
                // If the current rule applies to the current user
                if (user.User.Equals(currentRule.IdentityReference) || principal.IsInRole((SecurityIdentifier)currentRule.IdentityReference))
                {
                    if (diagnostics != null)
                    {
                        diagnostics.Add("Current process is a member of " + SidToAccountName(currentRule.IdentityReference));
                    }
                    if (currentRule.AccessControlType.Equals(AccessControlType.Deny))
                    {
                        if ((currentRule.FileSystemRights & FileSystemRights.Read) == FileSystemRights.Read)
                        {
                            denyRead = true;
                            if (diagnostics != null)
                            {
                                diagnostics.Add("Read access explicitly denied");
                            }
                        }
                    }
                    else if (currentRule.AccessControlType.Equals(AccessControlType.Allow))
                    {
                        if ((currentRule.FileSystemRights & FileSystemRights.Read) == FileSystemRights.Read)
                        {
                            allowRead = true;
                            if (diagnostics != null)
                            {
                                diagnostics.Add("Read access explicitly granted");
                            }
                        }
                    }
                }
                else if (diagnostics != null)
                {
                    diagnostics.Add("Current process is not a member of " + SidToAccountName(currentRule.IdentityReference));
                }
            }
            if (denyRead)
            {
                return(false);
            }
            if (allowRead)
            {
                return(true);
            }

            // Shouldn't get to here
            if (diagnostics != null)
            {
                diagnostics.Add("No Read access rules found for current user or role");
                diagnostics.Add("Read access not explicity granted");
            }

            return(false);
        }