Ejemplo n.º 1
0
        public string DecodeSID(SecurityIdentifier trustee, bool translateSid = true)
        {
            string ret = null;

            if (!translateSid)
            {
                ret = trustee.ToString() + " (must not resolve)";
            }

            else
            {
                try
                {
                    ret = ForestBase.SidCache.GetValueSafe <SecurityIdentifier, string>(trustee);

                    if (ret == null)
                    {
                        ret = trustee.Translate(typeof(NTAccount)).Value;
                    }
                }

                catch (Exception ex)
                {
                    ret = trustee.ToString() + " (could not resolve)";;

                    GlobalEventHandler.RaiseErrorOccured("ERROR resolving " + trustee.ToString());

                    ex.ToDummy();
                }

                ForestBase.SidCache.AddSafe <SecurityIdentifier, string>(trustee, ret);
            }

            return(ret);
        }
        DSNAME[] LookupSID(DsServer dc, uint flags, NT4SID sid)
        {
            List <DSNAME>      rt    = new List <DSNAME>();
            SecurityIdentifier secId = new SecurityIdentifier(sid.Data, 0);

            DSNAME[] rt1 = LookupAttr(dc, flags, "objectSid", secId.ToString());
            DSNAME[] rt2 = LookupAttr(dc, flags, "sIDHistory", secId.ToString());

            if (rt1 != null)
            {
                rt.AddRange(rt1);
            }
            if (rt2 != null)
            {
                rt.AddRange(rt2);
            }

            if (rt.Count > 0)
            {
                return(rt.ToArray());
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Walks through the config file extracting the data we need for the model.
        /// </summary>
        /// <param name="tcpHostingConfiguration"></param>
        private static void ReadConfiguration(Configuration tcpHostingConfiguration)
        {
            ConfigurationSectionGroup sg = tcpHostingConfiguration.SectionGroups[ServiceModelTag];
            ConfigurationSection      cs = sg.Sections[NetTcpTag];

            //avoid taking a dependency on System.ServiceModel,
            //use reflection to get the property collections we need.
            System.Reflection.PropertyInfo pi = cs.GetType().GetProperty(AllowAccountsTag);
            ConfigurationElementCollection allowedAccounts = (ConfigurationElementCollection)pi.GetValue(cs, null);

            //enumerates over System.ServiceModel.Activation.Configuration.SecurityIdentifierElement
            List <String> currentSids = new List <string>();

            foreach (ConfigurationElement securityIdentiferElement in allowedAccounts)
            {
                SecurityIdentifier sid = (SecurityIdentifier)securityIdentiferElement.GetType().GetProperty(SecurityIdentifierTag).GetValue(securityIdentiferElement, null);
                if (!currentSids.Contains(sid.ToString()))
                {
                    currentSids.Add(sid.ToString());
                }
            }

            foreach (string sid in currentSids)
            {
                if (!AllowAccounts.Contains(sid))
                {
                    AllowAccounts.Add(sid);
                }
            }
        }
Ejemplo n.º 4
0
        // Token: 0x0600095E RID: 2398 RVA: 0x00029CD8 File Offset: 0x00027ED8
        private static List <Tuple <string, KeyType> > GetSidKeys(ADObject adObject)
        {
            ArgumentValidator.ThrowIfNull("adObject", adObject);
            List <Tuple <string, KeyType> > list  = new List <Tuple <string, KeyType> >();
            SecurityIdentifier securityIdentifier = (SecurityIdentifier)adObject[ADMailboxRecipientSchema.Sid];

            if (null != securityIdentifier)
            {
                list.Add(new Tuple <string, KeyType>(securityIdentifier.ToString(), KeyType.Sid));
            }
            securityIdentifier = (SecurityIdentifier)adObject[ADRecipientSchema.MasterAccountSid];
            if (null != securityIdentifier)
            {
                list.Add(new Tuple <string, KeyType>(securityIdentifier.ToString(), KeyType.MasterAccountSid));
            }
            MultiValuedProperty <SecurityIdentifier> multiValuedProperty = (MultiValuedProperty <SecurityIdentifier>)adObject[ADMailboxRecipientSchema.SidHistory];

            if (multiValuedProperty != null)
            {
                foreach (SecurityIdentifier securityIdentifier2 in multiValuedProperty)
                {
                    list.Add(new Tuple <string, KeyType>(securityIdentifier2.ToString(), KeyType.SidHistory));
                }
            }
            return(list);
        }
Ejemplo n.º 5
0
        private static void GetLogonUserInfo(SecurityIdentifier sid, string smtpDomain, out string smtpAddress, out string displayName, out string puid)
        {
            string smtpAddressTemporary = sid.ToString();
            string displayNameTemporary = sid.ToString();
            string puidTemporary        = string.Empty;

            ADNotificationAdapter.RunADOperation(delegate()
            {
                IRecipientSession tenantOrRootOrgRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(true, ConsistencyMode.IgnoreInvalid, ADSessionSettings.RootOrgOrSingleTenantFromAcceptedDomainAutoDetect(smtpDomain), 339, "GetLogonUserInfo", "f:\\15.00.1497\\sources\\dev\\clients\\src\\Owa2\\Server\\Core\\attachment\\CachedAttachmentInfo.cs");
                PropertyDefinition[] properties = new PropertyDefinition[]
                {
                    ADRecipientSchema.PrimarySmtpAddress,
                    ADRecipientSchema.LegacyExchangeDN,
                    ADRecipientSchema.DisplayName,
                    ADUserSchema.NetID
                };
                ADRawEntry entry = tenantOrRootOrgRecipientSession.FindADRawEntryBySid(sid, properties);
                try
                {
                    CachedAttachmentInfo.SafeGetValue(entry, ADRecipientSchema.PrimarySmtpAddress, ref smtpAddressTemporary);
                    CachedAttachmentInfo.SafeGetValue(entry, ADRecipientSchema.DisplayName, ref displayNameTemporary);
                    CachedAttachmentInfo.SafeGetValue(entry, ADUserSchema.NetID, ref puidTemporary);
                }
                catch (NotInBagPropertyErrorException)
                {
                }
            });
            smtpAddress = smtpAddressTemporary;
            displayName = displayNameTemporary;
            puid        = puidTemporary;
        }
        public void ParsedToStringEqualsValue()
        {
            var value = SPY_Put_19550.ToString();

            Console.WriteLine(value);
            var sid2 = SecurityIdentifier.Parse(value);

            Assert.AreEqual(SPY_Put_19550, sid2);
        }
Ejemplo n.º 7
0
        private bool CitrixUPM()
        {
            if (!EventLog.SourceExists("Citrix Profile management"))
            {
                return(false);
            }

            string timestart        = LogonTime.ToString("s");
            string timeend          = LogonTime.AddHours(1).ToString("s");
            string StartQueryString =
                "<QueryList>\n" +
                "  <Query Id=\"0\" Path=\"Application\">\n" +
                "    <Select Path=\"Application\">\n" +
                "        *[System[(EventID=10) " +
                "            and TimeCreated[@SystemTime &gt; '" + timestart + "' and @SystemTime &lt; '" + timeend + "']" +
                "            and Provider[@Name='Citrix Profile management']]]\n" +
                "        and *[EventData[Data and (Data = \"" + UserName + "\")]]\n" +
                "    </Select>\n" +
                "  </Query>\n" +
                "</QueryList>";
            EventLogQuery  eventsQuery = new EventLogQuery("Citrix Profile management", PathType.FilePath, StartQueryString);
            EventLogReader logReader   = new EventLogReader(eventsQuery);
            EventRecord    e           = logReader.ReadEvent();

            if (e == null)
            {
                return(false);
            }

            upmStart = (DateTime)e.TimeCreated;
            string EndQueryString =
                "<QueryList>\n" +
                "  <Query Id=\"0\" Path=\"Microsoft-Windows-User Profile Service/Operational\">\n" +
                "    <Select Path=\"Microsoft-Windows-User Profile Service/Operational\">\n" +
                "        *[System[(EventID=1) " +
                "            and TimeCreated[@SystemTime &gt; '" + timestart + "' and @SystemTime &lt; '" + timeend + "']" +
                "            and Security[@UserID='" + UserSID.ToString() + "']]]\n" +
                "    </Select>\n" +
                "  </Query>\n" +
                "</QueryList>";

            eventsQuery = new EventLogQuery("Microsoft-Windows-User Profile Service/Operational", PathType.FilePath, EndQueryString);
            logReader   = new EventLogReader(eventsQuery);
            e           = logReader.ReadEvent();
            if (e == null)
            {
                return(false);
            }

            upmEnd = (DateTime)e.TimeCreated;
            return(true);
        }
Ejemplo n.º 8
0
        public string GetPathEnvironmentVariable(string domainName, string userName)
        {
            try
            {
                NTAccount          f         = new NTAccount(domainName, userName);
                SecurityIdentifier s         = (SecurityIdentifier)f.Translate(typeof(SecurityIdentifier));
                string             sidString = s.ToString();

                var regView        = (Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32);
                var baseKey        = RegistryKey.OpenBaseKey(RegistryHive.Users, regView);
                var baseKeyPath    = Path.Combine(sidString, "Environment");
                var environmentKey = baseKey.OpenSubKey(baseKeyPath);
                var variableNames  = environmentKey.GetValueNames();

                string pathVariableVal = string.Empty;
                foreach (var varName in variableNames)
                {
                    if (varName.ToLower().Equals("path"))
                    {
                        pathVariableVal = environmentKey.GetValue(varName).ToString();
                        break;
                    }
                }

                return(pathVariableVal);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 9
0
        public void SamrRidToSidForAlias()
        {
            aliasTestPrerequisite();
            createAlias();

            Site.Log.Add(LogEntryKind.TestStep, "SamrRidToSid: obtain the SID of an account, given a RID.");
            string groupPath = string.Format("LDAP://{0}/CN={1},{2}",
                                             _samrProtocolAdapter.pdcFqdn, testAliasName, _samrProtocolAdapter.primaryDomainUserContainerDN);
            DirectoryEntry     entry     = new DirectoryEntry(groupPath);
            SecurityIdentifier objSid    = new SecurityIdentifier((byte[])entry.Properties["objectSid"].Value, 0);
            string             objectSid = objSid.ToString();

            string[] sidArray = objectSid.Split('-');
            uint     rid      = Convert.ToUInt32(sidArray[sidArray.Length - 1]);
            _RPC_SID?sid;

            _samrProtocolAdapter.SamrRidToSid(_aliasHandle, rid, out sid);
            byte[] ia = sid.Value.IdentifierAuthority.Value;
            Site.Assert.AreEqual(sidArray[2], ia[ia.Length - 1].ToString(), "The IdentifierAuthority in Sid should be right.");
            Site.Assert.AreEqual(sidArray.Length - 3, (int)sid.Value.SubAuthorityCount, "The SubAuthority count should be right.");
            for (int i = 0; i < 5; i++)
            {
                Site.Assert.AreEqual(sidArray[i + 3], sid.Value.SubAuthority[i].ToString(), "The SubAuthority{0} should be right.", i);
            }
        }
Ejemplo n.º 10
0
        private static string GetNTAccountSecIdentifier()
        {
            NTAccount          nTAccount          = new NTAccount(WindowsIdentity.GetCurrent().Name);
            SecurityIdentifier securityIdentifier = (SecurityIdentifier)nTAccount.Translate(typeof(SecurityIdentifier));

            return(securityIdentifier.ToString());
        }
Ejemplo n.º 11
0
        static public IEnumerable GetAdmins()
        {
            //Get the Builtin Administrators Group name based on the SID (S-1-5-32-544)
            SecurityIdentifier Sid     = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
            NTAccount          LAdmins = (NTAccount)Sid.Translate(typeof(NTAccount));

            //Enumerate all members of the local Administrators Group
            DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",Computer");
            DirectoryEntry admGroup     = localMachine.Children.Find(LAdmins.Value.Split('\\')[1], "group");

            foreach (object obj in (IEnumerable)admGroup.Invoke("members", null))
            {
                using (DirectoryEntry user = new DirectoryEntry(obj))
                {
                    string sName = user.Path;
                    sName = sName.Replace("WinNT://", "");
                    if (sName.Contains(Environment.MachineName))
                    {
                        //Remove the Domain Name if it's a local User / Group
                        sName = sName.Remove(0, sName.LastIndexOf("/") + 1);
                    }
                    string sSID = "";
                    try
                    {
                        //Get the SID from each User/Group
                        byte[]             oSid = user.Properties["objectSid"].Value as byte[];
                        SecurityIdentifier SID  = new SecurityIdentifier(oSid, 0);
                        sSID = SID.ToString();
                    }
                    catch { }

                    yield return(new LocalAdmins(sName, sSID, user.SchemaClassName));
                }
            }
        }
Ejemplo n.º 12
0
        // To check if the required environment variable exists for the given User Name
        public bool EnvironmentVariableExists(string domainName, string userName)
        {
            try
            {
                NTAccount          f         = new NTAccount(domainName, userName);
                SecurityIdentifier s         = (SecurityIdentifier)f.Translate(typeof(SecurityIdentifier));
                string             sidString = s.ToString();

                var regView        = (Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32);
                var baseKey        = RegistryKey.OpenBaseKey(RegistryHive.Users, regView);
                var baseKeyPath    = Path.Combine(sidString, "Environment");
                var environmentKey = baseKey.OpenSubKey(baseKeyPath);
                var envVariable    = environmentKey.GetValue(EnvironmentVariableName);
                if (envVariable != null)
                {
                    EnvironmentVariableValue = envVariable.ToString();
                    return(true);
                }
                return(false);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// returns profiledir based on regkey
        /// </summary>
        /// <param name="sid"></param>
        /// <returns></returns>
        public static List <string> GetProfileDir(SecurityIdentifier sid)
        {
            List <string> ret = new List <string>();

            //"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\S-1-5-21-534125731-1308685933-1530606844-1000}"
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(ROOT_PROFILE_KEY))
            {
                if (key != null)
                {
                    foreach (string keyName in key.GetSubKeyNames())
                    {
                        if (keyName.Contains(sid.ToString())) //get the %SID% and %SID%.bak key
                        {
                            using (RegistryKey subKey = Registry.LocalMachine.OpenSubKey(string.Format("{0}\\{1}", ROOT_PROFILE_KEY, keyName)))
                            {
                                LibraryLogging.Info("ProfileList key found {0}", keyName);
                                ret.Add(subKey.GetValue("ProfileImagePath", "", RegistryValueOptions.None).ToString());
                            }
                        }
                    }
                }
                else
                {
                    LibraryLogging.Info("GetProfileDir key {0} not found", ROOT_PROFILE_KEY);
                }
            }

            return(ret);
        }
Ejemplo n.º 14
0
        public override bool Equals(Object obj)
        {
            var sid1 = obj as Sid;

            if (sid1 != null)
            {
                var s = sid1;
                if (s.sid != null)
                {
                    return(s.sid == sid);
                }
                return(s.SecurityIdentifier.ToLowerInvariant() == SecurityIdentifier.ToLowerInvariant());
            }
            var identifier = obj as SecurityIdentifier;

            if (identifier != null)
            {
                var s = identifier;
                return(s == sid);
            }
            if ((obj is string) || (obj is String))
            {
                var s = (String)obj;
                if (!String.IsNullOrEmpty(s))
                {
                    return(s == sid.ToString());
                }
            }
            return(false);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// This methods checks whether any of the specified SIDs belong to an administrator or are an administrator group
        /// </summary>
        /// <param name="SIDs"></param>
        /// <returns></returns>
        public static bool IsAdmin(List <string> SIDs)
        {
            SecurityIdentifier builtinAdminSid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);

            // In case SID belongs to a group we can directly compare the SID values
            foreach (var SID in SIDs)
            {
                if (builtinAdminSid.ToString().Equals(SID))
                {
                    return(true);
                }
            }

            // If it not we need to compare with the members of the builtin admin group
            PrincipalContext ctx   = new PrincipalContext(ContextType.Machine);
            GroupPrincipal   group = GroupPrincipal.FindByIdentity(ctx, builtinAdminSid.Value);

            foreach (Principal p in group.Members)
            {
                if (SIDs.Contains(p.Sid.ToString()))
                {
                    return(true);
                }
            }
            return(false);
        }
Ejemplo n.º 16
0
        private void UpdateOnedriveInfo()
        {
            onedriveButton.Enabled = false;
            //ModifyRegistry.ModifyRegistry userShellFolders = new ModifyRegistry.ModifyRegistry(Registry.CurrentUser, @"Microsoft", @"Windows\CurrentVersion\Explorer\User Shell Folders");
            ModifyRegistry.ModifyRegistry userShellFolders      = new ModifyRegistry.ModifyRegistry(Registry.CurrentUser, "Microsoft", @"Windows\CurrentVersion\Explorer\User Shell Folders");
            ModifyRegistry.ModifyRegistry onedriveFolder        = new ModifyRegistry.ModifyRegistry(Registry.CurrentUser, @"Microsoft", @"OneDrive\Accounts\Business1");
            ModifyRegistry.ModifyRegistry onedriveVersionFolder = new ModifyRegistry.ModifyRegistry(Registry.CurrentUser, @"Microsoft", @"Onedrive");


            string             user        = Environment.UserName;
            NTAccount          currentUser = new NTAccount(user);
            SecurityIdentifier sid         = (SecurityIdentifier)currentUser.Translate(typeof(SecurityIdentifier));

            SID.Text             = sid.ToString();
            desktopLocation.Text = userShellFolders.ReadString("{754AC886-DF64-4CBA-86B5-F7FBF4FBCEF5}");
            documents.Text       = userShellFolders.ReadString("Personal");
            deviceID.Text        = HardwareLibrary.DeviceID();
            LoadAdminGroup();

            bool onedriveInstalled = (onedriveFolder.ReadString(@"UserFolder") == null) ? false : true;

            if (onedriveInstalled)
            {
                onedrive.Text = onedriveFolder.ReadString("UserFolder");
                version.Text  = onedriveVersionFolder.ReadString("Version");
                Thread.Sleep(200);
                onedriveButton.Enabled = true;
            }
        }
Ejemplo n.º 17
0
        internal static UserContextKey CreateFromCookie(UserContextCookie userContextCookie, HttpContext httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            if (httpContext.User == null)
            {
                throw new ArgumentNullException("httpContext.User");
            }
            if (httpContext.User.Identity == null)
            {
                throw new ArgumentNullException("httpContext.User.Identity");
            }
            SecurityIdentifier securityIdentifier = httpContext.User.Identity.GetSecurityIdentifier();

            if (securityIdentifier == null)
            {
                ExTraceGlobals.UserContextCallTracer.TraceDebug(0L, "UserContextKey.CreateFromCookie: current user has no security identifier.");
                return(null);
            }
            string text = securityIdentifier.ToString();

            if (userContextCookie == null)
            {
                throw new ArgumentNullException("userContextCookie");
            }
            return(new UserContextKey(userContextCookie.UserContextId, text, userContextCookie.MailboxUniqueKey));
        }
Ejemplo n.º 18
0
        private String8 DecodeSid(String8 sidBytes)
        {
            // Slightly Horrible
            SecurityIdentifier sid = new SecurityIdentifier(sidBytes.Array, sidBytes.Index);

            return(_currentRowBlock.GetCopy(sid.ToString()));
        }
Ejemplo n.º 19
0
        internal static UserContextKey CreateNew(SecurityIdentifier sid)
        {
            string text  = null;
            string text2 = sid.ToString();

            return(UserContextKey.Create(UserContextUtilities.GetNewGuid(), text2, text));
        }
Ejemplo n.º 20
0
        private static void SetCurrentWallpaper(string uri, string id = null)
        {
            string sidString = null;

            try
            {
                if (String.IsNullOrEmpty(id))
                {
                    sidString = "default";
                }
                else
                {
                    NTAccount          account = new NTAccount(id);
                    SecurityIdentifier s       = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
                    sidString = s.ToString();
                    Console.WriteLine(sidString);
                }

                Wallpaper.Set(uri, sidString, Wallpaper.Style.Stretched);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 21
0
        public void SamrRidToSid()
        {
            Site.Log.Add(LogEntryKind.TestStep, "Connect and open a user handle.");
            ConnectAndOpenUser(_samrProtocolAdapter.PDCNetbiosName, _samrProtocolAdapter.PrimaryDomainDnsName,
                               _samrProtocolAdapter.DomainAdministratorName, out _userHandle);

            Site.Log.Add(LogEntryKind.TestStep, "SamrRidToSid: obtain the SID of an account, given a RID.");
            string userPath = string.Format("LDAP://{0}/CN={1},{2}",
                                            _samrProtocolAdapter.pdcFqdn, _samrProtocolAdapter.DomainAdministratorName, _samrProtocolAdapter.primaryDomainUserContainerDN);
            DirectoryEntry     entry     = new DirectoryEntry(userPath);
            SecurityIdentifier objSid    = new SecurityIdentifier((byte[])entry.Properties["objectSid"].Value, 0);
            string             objectSid = objSid.ToString();

            string[] sidArray = objectSid.Split('-');
            uint     rid      = Convert.ToUInt32(sidArray[sidArray.Length - 1]);
            _RPC_SID?sid;
            HRESULT  result = _samrProtocolAdapter.SamrRidToSid(_userHandle, rid, out sid);

            Site.Assert.AreEqual(HRESULT.STATUS_SUCCESS, result, "SamrRidToSid succeeded.");
            byte[] ia = sid.Value.IdentifierAuthority.Value;
            Site.Assert.AreEqual(sidArray[2], ia[ia.Length - 1].ToString(), "The IdentifierAuthority in Sid should be right.");
            Site.Assert.AreEqual(sidArray.Length - 3, (int)sid.Value.SubAuthorityCount, "The SubAuthority count should be right.");
            for (int i = 0; i < sid.Value.SubAuthority.Length; i++)
            {
                Site.Assert.AreEqual(sidArray[i + 3], sid.Value.SubAuthority[i].ToString(), "The SubAuthority{0} should be right.", i);
            }
        }
Ejemplo n.º 22
0
        public static DirectoryEntry FindById(string searchBase, SecurityIdentifier sid, string user, string pass, SearchScope scope)
        {
            var search = searchBase.StartsWith("LDAP://") ? searchBase : $"LDAP://{searchBase}";

            IDirectorySearch ds = GetDirectorySearcher(search);

            IntPtr searchHandle = IntPtr.Zero;

            int hr = ds.ExecuteSearch($"(objectSid={sid.ToString()})", _adProperties.ToArray(), _adProperties.Count, out searchHandle);

            if (Failed(hr))
            {
                throw ComException.BuildComException(hr, ds);
            }

            hr = ds.GetFirstRow(searchHandle);
            var de = new DirectoryEntry();

            foreach (var obj in _adProperties)
            {
                de.Add(obj, de.GetValue(ds, searchHandle, obj));
            }

            return(de);
        }
Ejemplo n.º 23
0
        private void ToStringFormButton_Click(object sender, EventArgs e)
        {
            var bytes = StringVarBinaryToByteArray(this.sourceSidText.Text);
            var securityIdentifier = new SecurityIdentifier(bytes, 0);

            this.ResultText.Text = securityIdentifier.ToString();
        }
Ejemplo n.º 24
0
        public static ActionResult GetFimGroups(Session session)
        {
            SecurityIdentifier sid = null;

            try
            {
                session.Log("Attempting to get administrators group SID");
                sid = SyncServer.GetAdministratorsGroupSid();
            }
            catch (Exception ex)
            {
                session.Log(ex.ToString());
            }

            if (sid == null)
            {
                session.Log("Get administrator group SID failed");
            }
            else
            {
                //#warning remove this
                //sid = (SecurityIdentifier)new NTAccount("Fim-dev1\\idm-gg-fimadmins").Translate(typeof(SecurityIdentifier));

                session.Log("Got administrators group SID");
                session["GROUP_FIM_SYNC_ADMINS"]      = sid.ToString();
                session["GROUP_FIM_SYNC_ADMINS_NAME"] = sid.Translate(typeof(NTAccount)).Value;
            }

            return(ActionResult.Success);
        }
Ejemplo n.º 25
0
        //load hives
        public static void loadUserRegistryHive(string username)
        {
            string wimHivePath = "C:\\Users\\" + username + "\\ntuser.dat";

            try
            {
                NTAccount          f         = new NTAccount(username);
                SecurityIdentifier s         = (SecurityIdentifier)f.Translate(typeof(SecurityIdentifier));
                string             sidString = s.ToString();

                string[] loadedHives   = Registry.Users.GetSubKeyNames();
                bool     foundUserName = false;

                foreach (string hiveName in loadedHives)
                {
                    if (hiveName.Equals(sidString))
                    {
                        foundUserName = true;
                    }
                }

                if (!foundUserName)
                {
                    string loadedHiveKey = RegistryInterop.Load(wimHivePath, sidString);

                    Console.WriteLine("Key Loaded: {0}", loadedHiveKey);
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Could not resolve sid for user: {0}", username);
            }
        }
Ejemplo n.º 26
0
        public static string GetProfileDir(SecurityIdentifier sid)
        {
            //"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\S-1-5-21-534125731-1308685933-1530606844-1000}"
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(ROOT_PROFILE_KEY))
            {
                if (key != null)
                {
                    foreach (string keyName in key.GetSubKeyNames())
                    {
                        if (keyName == sid.ToString())
                        {
                            using (RegistryKey subKey = Registry.LocalMachine.OpenSubKey(string.Format("{0}\\{1}", ROOT_PROFILE_KEY, keyName)))
                            {
                                return((string)subKey.GetValue("ProfileImagePath", null, RegistryValueOptions.None));
                            }
                        }
                    }

                    throw new KeyNotFoundException(string.Format("Unable to find value for: {0}", sid));
                }
                else
                {
                    throw new KeyNotFoundException(string.Format("Unable to open registry key"));
                }
            }
        }
Ejemplo n.º 27
0
        private string _TranslateUserNameToSid(string username)
        {
            NTAccount          ntAcct = new NTAccount(username);
            SecurityIdentifier sid    = (SecurityIdentifier)ntAcct.Translate(typeof(SecurityIdentifier));

            return(sid.ToString());
        }
Ejemplo n.º 28
0
        internal static string GetSID(string _userid)
        {
            NTAccount          acc = new NTAccount(_userid);
            SecurityIdentifier sid = (SecurityIdentifier)acc.Translate(typeof(SecurityIdentifier));

            return(sid.ToString());
        }
Ejemplo n.º 29
0
        private List <UserRefreshModel> GetAllUserData()
        {
            List <UserRefreshModel> model = new List <UserRefreshModel>();

            using (var context = new PrincipalContext(ContextType.Domain, "safety.northernsafety.com"))
            {
                using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
                {
                    foreach (var result in searcher.FindAll())
                    {
                        UserRefreshModel singleUser = new UserRefreshModel();

                        DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                        if (de != null && de.Properties["givenName"].Value != null && de.Properties["physicalDeliveryOfficeName"].Value != null && de.Properties["department"].Value != null)
                        {
                            singleUser.FirstName  = de.Properties["givenName"].Value.ToString();
                            singleUser.LastName   = de.Properties["sn"].Value != null ? de.Properties["sn"].Value.ToString() : "";
                            singleUser.EMail      = de.Properties["mail"].Value != null ? de.Properties["mail"].Value.ToString() : "";
                            singleUser.UserName   = de.Properties["sAMAccountName"].Value != null ? de.Properties["sAMAccountName"].Value.ToString() : "";
                            singleUser.Location   = de.Properties["physicalDeliveryOfficeName"].Value.ToString();
                            singleUser.Department = de.Properties["department"].Value.ToString();
                            var sidBytes           = (byte[])de.Properties["objectSid"].Value;
                            SecurityIdentifier sid = new SecurityIdentifier(sidBytes, 0);
                            singleUser.SID = sid.ToString();

                            model.Add(singleUser);
                        }
                    }
                }
            }

            return(model);
        }
Ejemplo n.º 30
0
        public static ObscureUrl CreatePublishReachCalendarUrl(string externalUrl, Guid mailboxGuid, string domain, string existingIdentity, SecurityIdentifier reachUserSid)
        {
            Util.ThrowOnNullOrEmptyArgument(externalUrl, "externalUrl");
            Util.ThrowOnNullOrEmptyArgument(domain, "domain");
            Util.ThrowOnNullArgument(reachUserSid, "reachUserSid");
            if (!ExternalUser.IsValidReachSid(reachUserSid))
            {
                throw new ArgumentException("Not an valid reach user sid.", "reachUserSid");
            }
            SharingDataType reachCalendar = SharingDataType.ReachCalendar;
            string          text          = string.IsNullOrEmpty(existingIdentity) ? Guid.NewGuid().ToString("N") : ObscureUrl.ParseGuidIdentity(reachCalendar, existingIdentity).ToString("N");
            string          text2         = ObscureUrl.CalculateHashString(ObscureKind.Normal, text);
            string          uriString     = string.Format("{0}/{1}/{2}@{3}/{4}{5}/{6}/{7}", new object[]
            {
                externalUrl.TrimEnd(new char[]
                {
                    '/'
                }),
                reachCalendar.ExternalName,
                mailboxGuid.ToString("N"),
                domain,
                text,
                text2,
                reachUserSid.ToString(),
                reachCalendar.PublishResourceName
            });
            ObscureUrl obscureUrl = new ObscureUrl(new Uri(uriString, UriKind.Absolute), reachCalendar, mailboxGuid, domain, text, ObscureKind.Normal, reachUserSid);

            ExTraceGlobals.SharingTracer.TraceDebug <ObscureUrl, string>(0L, "ObscureUrl.CreatePublishReachCalendarUrl(): Created an instance of ObscureUrl: {0} - {1}.", obscureUrl, obscureUrl.TraceInfo);
            return(obscureUrl);
        }