private static string GetAccountNameFromSID(string sidString)
        {
            SecurityIdentifier sid = new SecurityIdentifier(sidString);

            if (sid.IsAccountSid() && sid.IsValidTargetType(typeof(NTAccount)))
            {
                try
                {
                    NTAccount account = (NTAccount)sid.Translate(typeof(NTAccount));
                    return(account.Value);
                }
                catch (IdentityNotMappedException)
                { // Some or all identity references could not be translated.
                    return(null);
                }
                catch (System.ArgumentNullException)
                { // The target translation type is null.
                    return(null);
                }
                catch (System.ArgumentException)
                { // The target translation type is not an IdentityReference type.
                    return(null);
                }
                catch (System.SystemException)
                { // A Win32 error code was returned.
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
Пример #2
0
        /// <summary>
        /// Converts a SID to a user account name.
        /// </summary>
        public static string SidToAccountName(string sid)
        {
            SecurityIdentifier identifier = new SecurityIdentifier(sid);

            if (!identifier.IsValidTargetType(typeof(NTAccount)))
            {
                return(null);
            }

            return(identifier.Translate(typeof(NTAccount)).ToString());
        }
Пример #3
0
 public static string SidToAccountName(SecurityIdentifier sid)
 {
     try
     {
         return((sid.IsValidTargetType(typeof(NTAccount)))
              ? ((NTAccount)sid.Translate(typeof(NTAccount))).Value
              : sid.Value);
     }
     catch
     {
         return(sid.Value);
     }
 }
Пример #4
0
        private void GetWellKnownSid(bool domain)
        {
            SecurityIdentifier currDomain = null;

            if (domain)
            {
                currDomain = WindowsIdentity.GetCurrent().User.AccountDomainSid;
                Console.WriteLine("\n+++ Domain SID: {0} +++", currDomain);
            }


            foreach (WellKnownSidType wsid in Enum.GetValues(typeof(WellKnownSidType)))
            {
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.Write("{0}: ", wsid);
                Console.ResetColor();

                try
                {
                    SecurityIdentifier sid = new SecurityIdentifier(wsid, domain ? new SecurityIdentifier(currDomain.Value) : null);

                    try
                    {
                        Console.WriteLine("{0} , {1} ",
                                          (sid.IsValidTargetType(typeof(NTAccount)) ? sid.Translate(typeof(NTAccount)).ToString() : "-"),
                                          sid.Value
                                          );
                    }
                    catch (Exception e)
                    {
                        Console.ForegroundColor = ConsoleColor.DarkRed;
                        Console.WriteLine(" !{0}", e.Message);
                        Console.ResetColor();
                    }
                }
                catch (Exception e)
                {
                    Console.ForegroundColor = ConsoleColor.DarkMagenta;
                    Console.WriteLine(" !{0}", e.Message);
                    Console.ResetColor();
                }
            }
        }
Пример #5
0
        private void GetNTAcctForPath(String path)
        {
            FileSecurity fs = File.GetAccessControl(path);

            AuthorizationRuleCollection ntarc = fs.GetAccessRules(true, true, typeof(NTAccount));
            AuthorizationRuleCollection siarc = fs.GetAccessRules(true, true, typeof(SecurityIdentifier));

            Console.WriteLine("Checking SIDs on path: {0}", path);

            Console.WriteLine("\n== By NTAccount ==");
            foreach (FileSystemAccessRule fsar in ntarc)
            {
                NTAccount nta = (NTAccount)fsar.IdentityReference;
                Console.WriteLine("{0} <=> {1}", nta.Value, nta.IsValidTargetType(typeof(SecurityIdentifier)) ?
                                  nta.Translate(typeof(SecurityIdentifier)).ToString() :
                                  "-");
            }
            Console.WriteLine("\n== By SecurityIdentifier == ");
            foreach (FileSystemAccessRule siar in siarc)
            {
                SecurityIdentifier sia = (SecurityIdentifier)siar.IdentityReference;

                try
                {
                    Console.WriteLine("SDDL:{0} <=> {1}",
                                      sia.Value,
                                      (sia.IsAccountSid() ? (sia.IsValidTargetType(typeof(NTAccount)) ?
                                                             sia.Translate(typeof(NTAccount)).ToString() : "-") :
                                       "Not a real Windows Account"));
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: {0}", e.Message);
                }
            }
        }
Пример #6
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);
        }
Пример #7
0
        public ProgramInstallInfo(RegistryKey key)
        {
            Key = key;

            Comments       = GetValueAsString("Comments");
            Contact        = GetValueAsString("Contact");
            DisplayName    = GetValueAsString("DisplayName");
            DisplayVersion = GetValueAsString("DisplayVersion");
            EstimatedSize  = GetValueAsInt("EstimatedSize");
            HelpLink       = GetValueAsString("HelpLink");
            HelpTelephone  = GetValueAsString("HelpTelephone");

            var      installDateValue = GetValueAsString("InstallDate");
            DateTime installDate;

            if (!DateTime.TryParse(installDateValue, out installDate))
            {
                DateTime.TryParseExact(installDateValue, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out installDate);
            }
            InstallDate = installDate;

            InstallLocation = GetValueAsString("InstallLocation");
            InstallSource   = GetValueAsString("InstallSource");
            Language        = GetValueAsInt("Language");
            ModifyPath      = GetValueAsString("ModifyPath");
            Path            = GetValueAsString("Path");

            ProductCode = Guid.Empty;
            Guid productCode;
            var  keyName = System.IO.Path.GetFileName(key.Name);

            if (Guid.TryParse(keyName, out productCode))
            {
                ProductCode = productCode;
            }

            Publisher       = GetValueAsString("Publisher");
            Readme          = GetValueAsString("Readme");
            Size            = GetValueAsString("Size");
            UninstallString = GetValueAsString("UninstallString");
            UrlInfoAbout    = GetValueAsString("URLInfoAbout");
            UrlUpdateInfo   = GetValueAsString("URLUpdateInfo");

            User = String.Empty;
            if (key.Name.StartsWith("HKEY_USERS", StringComparison.InvariantCultureIgnoreCase))
            {
                var match = Regex.Match(key.Name, @"^HKEY_USERS\\([^\\]+)\\");
                if (match.Success)
                {
                    User = match.Groups[1].Value;
                    try
                    {
                        var sid = new SecurityIdentifier(User);
                        if (sid.IsValidTargetType(typeof(NTAccount)))
                        {
                            var ntAccount = sid.Translate(typeof(NTAccount)) as NTAccount;
                            if (ntAccount != null)
                            {
                                User = ntAccount.Value;
                            }
                        }
                    }
                    // ReSharper disable once EmptyGeneralCatchClause
                    catch (Exception)
                    {
                    }
                }
            }

            var    intVersion = GetValueAsInt("Version");
            string rawVersion;

            if (intVersion != 0)
            {
                var major = intVersion >> 24;                 // first 8 bits are major version number
                var minor = (intVersion & 0x00ff0000) >> 16;  // bits 9 - 16 are the minor version number
                var build = intVersion & 0x0000ffff;          // last 16 bits are the build number
                rawVersion = String.Format("{0}.{1}.{2}", major, minor, build);
            }
            else
            {
                rawVersion = GetValueAsString("Version");
            }

            Version version;

            if (Version.TryParse(rawVersion, out version))
            {
                Version = version;
            }

            VersionMajor = GetValueAsInt("VersionMajor");
            VersionMinor = GetValueAsInt("VersionMinor");

            var windowsInstallerValue = GetValueAsInt("WindowsInstaller");

            WindowsInstaller = (windowsInstallerValue > 0);
        }
Пример #8
0
        private void ImpersonateUser(String userName, String domainName)
        {
            if (domainName == null)
            {
                domainName = ".";
            }
            IntPtr tokenHandle = WindowsIdentity.GetCurrent().Token;

            Console.WriteLine("Before Impersonation");
            Console.WriteLine("Token {0}", tokenHandle);
            Console.WriteLine("Auth type: {0}", WindowsIdentity.GetCurrent().AuthenticationType);
            Console.WriteLine("Impersonation Level: {0}", WindowsIdentity.GetCurrent().ImpersonationLevel);
            Console.WriteLine("Owner of Process: {0}", WindowsIdentity.GetCurrent().Owner);
            Console.WriteLine("User: {0}", WindowsIdentity.GetCurrent().User);

            IntPtr phToken = IntPtr.Zero;

            SecureString pwd = new SecureString();

            // Use the AppendChar method to add each char value to the secure string.

            Console.Write("PW: ");
            char[] che = Console.ReadLine().TrimEnd(Environment.NewLine.ToCharArray()).ToCharArray();
            foreach (char ch in che)
            {
                pwd.AppendChar(ch);
            }

            IntPtr pwdPtr = Marshal.SecureStringToGlobalAllocUnicode(pwd);
            bool   status;

            status = LogonUser(userName, domainName, pwdPtr, 3, 3, out phToken);
            pwd.Dispose();

            if (status)
            {
                Console.WriteLine("Impersonating token {0} with token {1}", tokenHandle, phToken);
                try
                {
                    using (WindowsImpersonationContext wic = WindowsIdentity.Impersonate(phToken))
                    {
                        SecurityIdentifier ownerSid = WindowsIdentity.GetCurrent().Owner;
                        SecurityIdentifier userSid  = WindowsIdentity.GetCurrent().User;

                        Console.WriteLine("After Impersonation");
                        Console.WriteLine("Token {0}", WindowsIdentity.GetCurrent().Token);
                        Console.WriteLine("|-Name {0}", WindowsIdentity.GetCurrent().Name);
                        Console.WriteLine("|-Auth type: {0}", WindowsIdentity.GetCurrent().AuthenticationType);
                        Console.WriteLine("|-Impersonation Level: {0}", WindowsIdentity.GetCurrent().ImpersonationLevel);
                        Console.WriteLine("|-Owner of Process: {0} {1}", ownerSid,
                                          (ownerSid.IsValidTargetType(typeof(NTAccount)) ?
                                           ownerSid.Translate(typeof(NTAccount)).ToString() : "-")
                                          );
                        Console.WriteLine("|-User: {0} {1}", userSid,
                                          (userSid.IsValidTargetType(typeof(NTAccount)) ?
                                           userSid.Translate(typeof(NTAccount)).ToString() : "-")
                                          );
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Impersonation failed: {0}", e.Message);
                }
            }
            else
            {
                int err = Marshal.GetLastWin32Error();
                if (err != 0)
                {
                    Console.Write("Unable to Impersonate");
                    Console.WriteLine(" : {0}  - {1} ", err, new Win32Exception(err).Message);
                }
            }
        }