public static string verifyNTuser(string userName)
        {
            DirectoryEntry dEntry = new DirectoryEntry("LDAP://ds.kycourts.net/CN=Users,DC=ds,DC=kycourts,DC=net");

            DirectorySearcher dSearch = new DirectorySearcher(dEntry);
            dSearch.PageSize = 6000;
            dSearch.Filter = "cn="+userName;
            dSearch.PropertiesToLoad.Add("cn");
            dSearch.PropertiesToLoad.Add("mail");
            dSearch.PropertiesToLoad.Add("objectSid");
            dSearch.CacheResults = true;
            if (dSearch.FindAll().Count > 0)
            {
                foreach (SearchResult sResultSet in dSearch.FindAll())
                {
                    SecurityIdentifier sid = new SecurityIdentifier((byte[])sResultSet.Properties["objectSid"][0], 0);
                    string[] namesid = sid.ToString().Split('-');
                    dEntry.Close();
                    return sResultSet.Properties["cn"][0].ToString() + ";" + sResultSet.Properties["mail"][0].ToString() + ";" +
                        namesid[namesid.Length - 1].ToString();

                }

            }
            else
            {
                dEntry.Close();
                return "false";
            }

            return "false";
        }
        public static ActiveDirectoryRole CreateFromSecurityIdentifier(SecurityIdentifier sid)
        {
            if (sid == null)
                throw new ArgumentNullException("sid");

            ActiveDirectoryRole role = new ActiveDirectoryRole(GetRootEntry(), new DirectoryRootQuery("objectSID", sid.ToString(), DirectoryQueryOperation.Equal));
            role.Operations.Add(s_directoryGroupQuery);
            ValidateRole(role);
            return role;
        }
示例#3
0
 public static string GetPropertyAsSID(this DirectoryEntry entry, string name)
 {
     if (entry.Properties.Contains(name))
     {
         byte[]             byteArray = (byte[])entry.Properties[name][0];
         SecurityIdentifier si        = new SecurityIdentifier(byteArray, 0);
         return(si.ToString());
     }
     else
     {
         return(string.Empty);
     }
 }
示例#4
0
        //make this searching the GC
        public static bool LookUpAcctSid(string contextSystem, byte[] abSID, StringBuilder sbDomain)
        {
            SecurityIdentifier sid = new SecurityIdentifier(abSID, 0);

            string[] splits = contextSystem.Split('.');

            string sDCs = "";

            foreach (string split in splits)
            {
                sDCs = string.Concat(sDCs, "DC=", split, ",");
            }

            sDCs = sDCs.Substring(0, sDCs.Length - 1);

            //some hack to obtain the creds to establish a GC dirContext [Wei]
            string username = string.Empty;
            string password = string.Empty;

            DirectoryEntry.ObtainCreds(out username, out password, contextSystem.ToLower());

            GlobalCatalog gc = GlobalCatalog.GetGlobalCatalog(
                new System.DirectoryServices.ActiveDirectory.DirectoryContext(DirectoryContextType.Domain, contextSystem.ToLower(),
                                                                              username, password));

            if (gc == null) //cannot talk to GC
            {
                string contextldapPath = string.Concat("LDAP://", contextSystem.ToLower(), "/", sDCs);

                DirectoryEntry context = new DirectoryEntry(contextldapPath);

                string filter = string.Concat("(objectSid=", sid.ToString(), ")");

                DirectorySearcher ds = new DirectorySearcher(context, filter);

                ds.SearchScope = SearchScope.Subtree;

                SearchResult de = ds.FindOne();

                if (de == null)
                {
                    //Console.WriteLine("GetSidDomain::LookUpAcctSid (Not Found!)");
                    return(false);
                }
                else
                {
                    //Console.WriteLine("GetSidDomain::LookUpAcctSid (Found!)");
                    sbDomain.Append(contextSystem);
                    return(true);
                }
            }
            else //search in GC
            {
                DirectorySearcher ds = gc.GetDirectorySearcher();
                ds.Filter      = string.Concat("(objectSid=", sid.ToString(), ")");
                ds.SearchScope = SearchScope.Subtree;
                SearchResult sr = ds.FindOne();
                if (sr == null)
                {
                    //Console.WriteLine("GetSidDomain::LookUpAcctSid (Not Found!) (in GC)");
                    return(false);
                }
                else
                {
                    //Console.WriteLine("GetSidDomain::LookUpAcctSid (Found!) (in GC)");
                    sbDomain.Append(contextSystem);
                    return(true);
                }
            }
        }
        private static string GetObjectSid(System.DirectoryServices.ResultPropertyCollection props, string name)
        {
            if (!props.Contains(name))
            {
                return string.Empty;
            }

            ResultPropertyValueCollection pvc = props[name];
            if (pvc == null || pvc.Count == 0)
            {
                return string.Empty;
            }

            byte[] sidInBytes = (byte[])pvc[0];
            SecurityIdentifier sid = new SecurityIdentifier(sidInBytes, 0);
            return sid.ToString();
        }
示例#6
0
        public static UsuarioActiveDirectoryBD AutenticarAD(string login, string senha, string nomGrupo)
        {
            bool valido = false;

            DirectoryEntry de = null;
            DirectoryEntry deUser = null;
            DirectoryEntry deGroup = null;
            DirectorySearcher deSearchUser = null;
            DirectorySearcher deSearchGroup = null;

            UsuarioActiveDirectoryBD usuarioAD = null;
            List<GrupoActiveDirectoryBD> listaGruposAD = new List<GrupoActiveDirectoryBD>();

            WS.srvParametros srvParametros = new WS.srvParametros();

            using (de = GetDirectoryObject("LDAP://" + srvParametros.ActiveDirectoryIP(), login, senha))
            {
                using (deSearchUser = new DirectorySearcher())
                {
                    deSearchUser.SearchRoot = de;
                    deSearchUser.Filter = "(&(objectClass=user)(objectCategory=person)(SamAccountName=" + login + "))";
                    deSearchUser.SearchScope = SearchScope.Subtree;

                    try
                    {
                        SearchResult results = deSearchUser.FindOne();

                        if (results != null)
                        {
                            using (deUser = new DirectoryEntry(results.Path, login, senha, AuthenticationTypes.Secure))
                            {
                                System.DirectoryServices.PropertyCollection propertiesUser = deUser.Properties;

                                //512 - Conta habilitada 514 - Conta desabilitada
                                if (propertiesUser["UserAccountControl"].ToString() == "514")
                                {
                                    new Exception("Conta desabilitada.");
                                }

                                if (propertiesUser["UserAccountControl"].ToString() == "8388608")
                                {
                                    new Exception("Senha expirada.");
                                }

                                SecurityIdentifier sidUser = new SecurityIdentifier(propertiesUser["objectSid"][0] as byte[], 0);

                                    usuarioAD = new UsuarioActiveDirectoryBD();
                                    usuarioAD.sid = sidUser.ToString();
                                    usuarioAD.nome = propertiesUser["displayname"].Value.ToString();
                                    usuarioAD.login = login;
                                    usuarioAD.senha = senha;

                                    string dominio = srvParametros.DominioFrescatto();
                                    string ActiveDirectoryIP = srvParametros.ActiveDirectoryIP();

                                    PrincipalContext context = new PrincipalContext(ContextType.Domain, ActiveDirectoryIP, login + "@" + dominio, senha);
                                    {
                                        using (UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, login))
                                        {
                                            foreach (Principal p in user.GetGroups())
                                            {
                                                if (p.Name.IndexOf(nomGrupo) != -1)
                                                {
                                                    GrupoActiveDirectoryBD grupoAD = new GrupoActiveDirectoryBD();
                                                    grupoAD.sidGrupo = p.Sid.ToString();
                                                    grupoAD.nomGrupo = p.Name;

                                                    listaGruposAD.Add(grupoAD);

                                                    valido = true;
                                                }

                                                //if (!valido)
                                                if (valido)
                                                {
                                                    foreach (Principal m in p.GetGroups(context))
                                                    {
                                                        GroupPrincipal group2 = GroupPrincipal.FindByIdentity(context, IdentityType.Name, m.Name);

                                                        if (group2 != null)
                                                        {
                                                            valido = true;

                                                            SecurityIdentifier sidGroup = group2.Sid;

                                                            GrupoActiveDirectoryBD grupoAD = new GrupoActiveDirectoryBD();
                                                            grupoAD.sidGrupo = sidGroup.Value;
                                                            grupoAD.nomGrupo = m.Name;

                                                            listaGruposAD.Add(grupoAD);
                                                        }
                                                    }

                                                    string grupo = string.Empty;
                                                    using (deGroup = new DirectoryEntry(results.Path + "/" + p.Name, login, senha, AuthenticationTypes.Secure))
                                                    {
                                                        string memberOf = p.Name;

                                                        deSearchGroup = new DirectorySearcher();
                                                        deSearchGroup.SearchRoot = new DirectoryEntry("LDAP://" + srvParametros.ActiveDirectoryIP() + "/" + memberOf, login, senha);
                                                        deSearchGroup.SearchScope = SearchScope.Subtree;
                                                        deSearchGroup.Filter = String.Format("(&(ObjectCategory=group)(SamAccountName={0}))", memberOf);

                                                        try
                                                        {
                                                            SearchResult sr = deSearchGroup.FindOne();

                                                            if (sr != null)
                                                            {
                                                                System.DirectoryServices.PropertyCollection groupProperties = deSearchGroup.SearchRoot.Properties;

                                                                for (int m = 0; m < groupProperties["memberOf"].Count; m++)
                                                                {
                                                                    string grupoSistema = string.Empty;

                                                                    string memberOfSistemas = groupProperties["memberOf"][m].ToString();

                                                                    int pos_ = memberOfSistemas.IndexOf("CN=");

                                                                    if (pos_ != -1)
                                                                    {
                                                                        for (int n = pos_ + 3; n < memberOfSistemas.Length; n++)
                                                                        {
                                                                            if (memberOfSistemas.Substring(n, 1) != ",")
                                                                            {
                                                                                grupoSistema += memberOfSistemas.Substring(n, 1);
                                                                            }
                                                                            else
                                                                            {
                                                                                n = memberOfSistemas.Length;
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        catch (Exception)
                                                        {
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    #region Obter grupos (antigo)
                                    /*
                                    for (int i = 0; i < propertiesUser["memberOf"].Count; i++)
                                    {
                                        string grupo = string.Empty;
                                        using (deGroup = new DirectoryEntry(results.Path + "/" + propertiesUser["memberOf"][i], login, senha, AuthenticationTypes.Secure))
                                        //using (deGroup = new DirectoryEntry(results.Path + "/" + p.Name, login, senha, AuthenticationTypes.Secure))
                                        {
                                            string memberOf = propertiesUser["memberOf"][i].ToString();
                                            //string memberOf = p.Name;

                                            int pos = memberOf.IndexOf("CN=");

                                            if (pos != -1)
                                            {
                                                for (int j = pos + 3; j < memberOf.Length; j++)
                                                {
                                                    if (memberOf.Substring(j, 1) != ",")
                                                    {
                                                        grupo += memberOf.Substring(j, 1);
                                                    }
                                                    else
                                                    {
                                                        j = memberOf.Length;
                                                    }
                                                }
                                            }

                                            deSearchGroup = new DirectorySearcher();
                                            deSearchGroup.SearchRoot = new DirectoryEntry("LDAP://" + FrescattoConnection.sPathAD + "/" + memberOf, login, senha);
                                            deSearchGroup.SearchScope = SearchScope.Subtree;
                                            deSearchGroup.Filter = String.Format("(&(ObjectCategory=group)(SamAccountName={0}))", grupo);

                                            SearchResult sr = deSearchGroup.FindOne();

                                            if (sr != null)
                                            {
                                                System.DirectoryServices.PropertyCollection groupProperties = deSearchGroup.SearchRoot.Properties;

                                                for (int m = 0; m < groupProperties["memberOf"].Count; m++)
                                                {
                                                    string grupoSistema = string.Empty;

                                                    string memberOfSistemas = groupProperties["memberOf"][m].ToString();

                                                    int pos_ = memberOfSistemas.IndexOf("CN=");

                                                    if (pos_ != -1)
                                                    {
                                                        for (int n = pos_ + 3; n < memberOfSistemas.Length; n++)
                                                        {
                                                            if (memberOfSistemas.Substring(n, 1) != ",")
                                                            {
                                                                grupoSistema += memberOfSistemas.Substring(n, 1);
                                                            }
                                                            else
                                                            {
                                                                n = memberOfSistemas.Length;
                                                            }
                                                        }
                                                    }

                                                    PrincipalContext ctx2 = new PrincipalContext(ContextType.Domain, FrescattoConnection.sPathAD, "OU=Sistemas,OU=Frescatto,DC=frescatto,DC=com", ContextOptions.SimpleBind, login + "@" + FrescattoConnection.sDominio, senha);
                                                    GroupPrincipal group2 = GroupPrincipal.FindByIdentity(ctx2, IdentityType.Name, grupoSistema);

                                                    if (group2 != null)
                                                    {
                                                        valido = true;

                                                        SecurityIdentifier sidGroup = group2.Sid;

                                                        GrupoActiveDirectoryBD grupoAD = new GrupoActiveDirectoryBD();
                                                        grupoAD.sidGrupo = sidGroup.Value;
                                                        grupoAD.nomGrupo = grupoSistema;

                                                        listaGruposAD.Add(grupoAD);
                                                    }
                                                }
                                            }
                                        }
                                    }*/
                                    #endregion
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        //throw new Exception(Messages.message3);
                        throw new Exception("Erro na autenticação com o AD. " + ex.Message);
                    }
                }
            }

            if (valido)
            {
                usuarioAD.grupos = listaGruposAD;
            }
            else
            {
                usuarioAD = null;
            }

            return usuarioAD;
        }
        public static string FindGroup(SecurityIdentifier searchSid)
        {
            using(var ad = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"))
            {
                ad.Children.SchemaFilter.Add("group");
                foreach(DirectoryEntry dChildEntry in ad.Children)
                {
                    var bytes = (byte[])dChildEntry.Properties["objectSid"].Value;
                    var sid = new SecurityIdentifier(bytes, 0).ToString();

                    if(sid == searchSid.ToString())
                    {
                        return dChildEntry.Name;
                    }
                }
            }
            throw new Exception("Cannot find group");
        }
示例#8
0
        // Advance the enumerator to the next principal in the result set, pulling in additional pages
        // of results (or ranges of attribute values) as needed.
        // Returns true if successful, false if no more results to return.
        override internal bool MoveNext()
        {
            if (_atBeginning)
            {
                Debug.Assert(_principalDN != null);

                _current = SDSUtils.BuildDirectoryEntry(
                                            BuildPathFromDN(_principalDN),
                                            _storeCtx.Credentials,
                                            _storeCtx.AuthTypes);

                _current.RefreshCache(new string[] { _attributeToQuery });

                _tokenGroupsEnum = _current.Properties[_attributeToQuery].GetEnumerator();

                _atBeginning = false;
            }

            GlobalDebug.WriteLineIf(GlobalDebug.Info, "TokenGroupSet", "MoveNextLocal: returning primary group {0}", _current.Path);

            if (_tokenGroupsEnum.MoveNext())
            {
                // Got a member from this group (or, got a group of which we're a member).
                // Create a DirectoryEntry for it.

                byte[] sid = (byte[])_tokenGroupsEnum.Current;
                _currentSID = new SecurityIdentifier(sid, 0);
                GlobalDebug.WriteLineIf(GlobalDebug.Info, "TokenGroupSet", "MoveNextLocal: got a value from the enumerator: {0}", _currentSID.ToString());

                return true;
            }

            return false;
        }
示例#9
0
 public static string GetSID(DirectoryEntry item, string ADpropName)
 {
     string SID = "";
     if (item.Properties.Contains(ADpropName))
     {
         try
         {
             SecurityIdentifier sid = new SecurityIdentifier(
                 item.Properties[ADpropName][0] as byte[], 0);
             SID = sid.ToString();
         }
         catch (Exception ex)
         {
             SqlContext.Pipe.Send("Warning: GetSID (" + ADpropName + ") failed for object (" + GetDistinguishedName(item) + ")"
                     + " Exception: " + ex.Message);
         }
     }
     return SID;
 }
示例#10
0
 public static UserPrincipal GetUserPrincipal(SecurityIdentifier sid)
 {
     // This could be updated to use PrincipalSearcher, but the method is currently
     // unused.
     return UserPrincipal.FindByIdentity(m_machinePrincipal, IdentityType.Sid, sid.ToString());
 }
示例#11
0
        //
        // Cross-store support
        //

        // Given a native store object that represents a "foreign" principal (e.g., a FPO object in this store that 
        // represents a pointer to another store), maps that representation to the other store's StoreCtx and returns 
        // a Principal from that other StoreCtx.  The implementation of this method is highly dependent on the
        // details of the particular store, and must have knowledge not only of this StoreCtx, but also of how to
        // interact with other StoreCtxs to fulfill the request.
        //
        // This method is typically used by ResultSet implementations, when they're iterating over a collection
        // (e.g., of group membership) and encounter a entry that represents a foreign principal.
        internal override Principal ResolveCrossStoreRefToPrincipal(object o)
        {
            Debug.Assert(o is DirectoryEntry);

            // Get the SID of the foreign principal
            DirectoryEntry foreignDE = (DirectoryEntry)o;

            if (foreignDE.Properties["objectSid"].Count == 0)
            {
                GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ResolveCrossStoreRefToPrincipal: no objectSid found");
                throw new PrincipalOperationException(StringResources.SAMStoreCtxCantRetrieveObjectSidForCrossStore);
            }

            Debug.Assert(foreignDE.Properties["objectSid"].Count == 1);

            byte[] sid = (byte[])foreignDE.Properties["objectSid"].Value;

            // Ask the OS to resolve the SID to its target.
            int accountUsage = 0;
            string name;
            string domainName;

            int err = Utils.LookupSid(this.MachineUserSuppliedName, _credentials, sid, out name, out domainName, out accountUsage);

            if (err != 0)
            {
                GlobalDebug.WriteLineIf(GlobalDebug.Warn,
                                        "SAMStoreCtx",
                                        "ResolveCrossStoreRefToPrincipal: LookupSid failed, err={0}, server={1}",
                                        err,
                                        this.MachineUserSuppliedName);

                throw new PrincipalOperationException(
                            String.Format(CultureInfo.CurrentCulture,
                                          StringResources.SAMStoreCtxCantResolveSidForCrossStore,
                                          err));
            }

            GlobalDebug.WriteLineIf(GlobalDebug.Info,
                                    "SAMStoreCtx",
                                    "ResolveCrossStoreRefToPrincipal: LookupSid found {0} in {1}",
                                    name,
                                    domainName);

            // Since this is SAM, the remote principal must be an AD principal.
            // Build a PrincipalContext for the store which owns the principal
            // Use the ad default options so we turn sign and seal back on.
#if USE_CTX_CACHE
            PrincipalContext remoteCtx = SDSCache.Domain.GetContext(domainName, _credentials, DefaultContextOptions.ADDefaultContextOption);
#else
            PrincipalContext remoteCtx = new PrincipalContext(
                            ContextType.Domain,
                            domainName,
                            null,
                            (this.credentials != null ? credentials.UserName : null),
                            (this.credentials != null ? credentials.Password : null),
                            DefaultContextOptions.ADDefaultContextOption);
            
#endif

            SecurityIdentifier sidObj = new SecurityIdentifier(sid, 0);

            Principal p = remoteCtx.QueryCtx.FindPrincipalByIdentRef(
                                            typeof(Principal),
                                            UrnScheme.SidScheme,
                                            sidObj.ToString(),
                                            DateTime.UtcNow);

            if (p != null)
                return p;
            else
            {
                GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "ResolveCrossStoreRefToPrincipal: no matching principal");
                throw new PrincipalOperationException(StringResources.SAMStoreCtxFailedFindCrossStoreTarget);
            }
        }
示例#12
0
 public ADDomain GetDomainFromSecurityIdentifier(SecurityIdentifier SecurityIdentifier)
 {
     ADDomain domain;
     if (!TryGetDomainFromSecurityIdentifier(SecurityIdentifier, out domain))
         throw new ArgumentException(string.Format("The domain for specified Security Identifier is unknown [{0}]", SecurityIdentifier.ToString()), "SecurityIdentifier");
     return domain;
 }
示例#13
0
		internal override Principal ResolveCrossStoreRefToPrincipal(object o)
		{
			string str = null;
			string str1 = null;
			DirectoryEntry directoryEntry = (DirectoryEntry)o;
			if (directoryEntry.Properties["objectSid"].Count != 0)
			{
				byte[] value = (byte[])directoryEntry.Properties["objectSid"].Value;
				int num = 0;
				int num1 = Utils.LookupSid(this.MachineUserSuppliedName, this.credentials, value, out str, out str1, out num);
				if (num1 == 0)
				{
					PrincipalContext context = SDSCache.Domain.GetContext(str1, this.credentials, DefaultContextOptions.ADDefaultContextOption);
					SecurityIdentifier securityIdentifier = new SecurityIdentifier(value, 0);
					Principal principal = context.QueryCtx.FindPrincipalByIdentRef(typeof(Principal), "ms-sid", securityIdentifier.ToString(), DateTime.UtcNow);
					if (principal == null)
					{
						throw new PrincipalOperationException(StringResources.SAMStoreCtxFailedFindCrossStoreTarget);
					}
					else
					{
						return principal;
					}
				}
				else
				{
					object[] objArray = new object[1];
					objArray[0] = num1;
					throw new PrincipalOperationException(string.Format(CultureInfo.CurrentCulture, StringResources.SAMStoreCtxCantResolveSidForCrossStore, objArray));
				}
			}
			else
			{
				throw new PrincipalOperationException(StringResources.SAMStoreCtxCantRetrieveObjectSidForCrossStore);
			}
		}
示例#14
0
        // Handles all the work required to implement FindPrincipalByIdentRef (and FindPrincipalBySID).
        private Principal FindPrincipalByIdentRefHelper(
                                    Type principalType,
                                    string urnScheme,
                                    string urnValue,
                                    DateTime referenceDate,
                                    bool useSidHistory)
        {
            GlobalDebug.WriteLineIf(GlobalDebug.Info,
                                    "ADStoreCtx",
                                    "FindPrincipalByIdentRefHelper: type={0}, scheme={1}, value={2}, useSidHistory={3}",
                                    principalType.ToString(),
                                    (urnScheme != null ? urnScheme : "NULL"),
                                    (urnValue != null ? urnValue : "NULL"),
                                    useSidHistory);

            //
            // Set up a DirectorySearcher
            //
            DirectorySearcher ds = new DirectorySearcher(this.ctxBase);
            SearchResultCollection src = null;

            try
            {
                ds.SizeLimit = 2;   // so we can efficiently check for duplicates

                // If we are searching for AuthPrincpal or Principal in the end we will construct the acutal type
                // i.e. if the objects objectClass is User we will construct a UserPrincipal even though they searched for Principal.FindByIdentity
                // At this time we don't know the actual object type so we have to ask AD for all the attributes of the derived types so they are there
                // when we go to load the principal.
                if (principalType == typeof(Principal) || principalType == typeof(AuthenticablePrincipal))
                {
                    BuildPropertySet(typeof(UserPrincipal), ds.PropertiesToLoad);
                    BuildPropertySet(typeof(GroupPrincipal), ds.PropertiesToLoad);
                    BuildPropertySet(typeof(ComputerPrincipal), ds.PropertiesToLoad);

                    if (principalType == typeof(Principal))
                    {
                        BuildPropertySet(typeof(AuthenticablePrincipal), ds.PropertiesToLoad);
                    }
                }

                BuildPropertySet(principalType, ds.PropertiesToLoad);

                //
                // Build an appropriate filter
                //

                StringBuilder ldapFilter = new StringBuilder();

                // Limit the results returned to principalType by specifying the corresponding objectClass/objectCategory
                ldapFilter.Append(GetObjectClassPortion(principalType));

                // Build the rest of the filter based off of the user's specified IdentityReference.
                if (urnScheme != null)
                {
                    // If they're searching by SID for a SID corresponding to a fake group, construct
                    // and return the fake group
                    if ((urnScheme == UrnScheme.SidScheme) &&
                         (principalType == typeof(Principal) || principalType == typeof(GroupPrincipal) || principalType.IsSubclassOf(typeof(GroupPrincipal))))
                    {
                        SecurityIdentifier sid = new SecurityIdentifier(urnValue);
                        byte[] sidb = new byte[sid.BinaryLength];
                        sid.GetBinaryForm(sidb, 0);
                        //                        = Utils.StringToByteArray(urnValue);

                        if (sid == null)
                            throw new ArgumentException(StringResources.StoreCtxSecurityIdentityClaimBadFormat);

                        IntPtr pSid = IntPtr.Zero;

                        try
                        {
                            pSid = Utils.ConvertByteArrayToIntPtr(sidb);

                            if (UnsafeNativeMethods.IsValidSid(pSid) && (Utils.ClassifySID(pSid) == SidType.FakeObject))
                            {
                                GlobalDebug.WriteLineIf(GlobalDebug.Info,
                                                        "ADStoreCtx",
                                                        "FindPrincipalByIdentRefHelper: fake principal, SID Scheme, {0}",
                                                        sid.ToString());

                                return ConstructFakePrincipalFromSID(sidb);
                            }
                        }
                        finally
                        {
                            if (pSid != IntPtr.Zero)
                                Marshal.FreeHGlobal(pSid);
                        }
                    }

                    // This is the simple case --- we got a specific UrnScheme, so we'll just build
                    // a filter for it.

                    // Ignore referenceDate --- all IdentityClaims in AD are forever
                    string innerLdapFilter = null;
                    BuildLdapFilterFromIdentityClaim(urnValue, urnScheme, ref innerLdapFilter, useSidHistory, true);

                    ldapFilter.Append(innerLdapFilter);
                }
                else
                {
                    // Are they perhaps searching for a fake group?
                    // If they passed in a valid SID for a fake group, construct and return the fake
                    // group.                
                    if (principalType == typeof(Principal) || principalType == typeof(GroupPrincipal) || principalType.IsSubclassOf(typeof(GroupPrincipal)))
                    {
                        SecurityIdentifier sid = null;
                        byte[] sidb = null;
                        try
                        {
                            sid = new SecurityIdentifier(urnValue);
                            sidb = new byte[sid.BinaryLength];
                            sid.GetBinaryForm(sidb, 0);
                        }
                        catch (ArgumentException)
                        {
                        }

                        if (sidb != null)
                        {
                            // They passed in a hex string, is it a valid SID, and if so, does it correspond to a fake
                            // principal?
                            IntPtr pSid = IntPtr.Zero;

                            try
                            {
                                pSid = Utils.ConvertByteArrayToIntPtr(sidb);

                                if (UnsafeNativeMethods.IsValidSid(pSid) && (Utils.ClassifySID(pSid) == SidType.FakeObject))
                                {
                                    GlobalDebug.WriteLineIf(GlobalDebug.Info,
                                                            "ADStoreCtx",
                                                            "FindPrincipalByIdentRefHelper: fake principal, null Scheme, {0}",
                                                            sid.ToString());

                                    return ConstructFakePrincipalFromSID(sidb);
                                }
                            }
                            finally
                            {
                                if (pSid != IntPtr.Zero)
                                    Marshal.FreeHGlobal(pSid);
                            }
                        }
                    }

                    // This is the tricky case.  They didn't specify a UrnScheme, so we need to
                    // try all of them.

                    string[] urnSchemesToTry = new string[]
                    {
                        UrnScheme.SamAccountScheme,
                        UrnScheme.UpnScheme,
                        UrnScheme.DistinguishedNameScheme,
                        UrnScheme.SidScheme,
                        UrnScheme.GuidScheme,
                        UrnScheme.NameScheme
                    };

                    StringBuilder innerLdapFilter = new StringBuilder();

                    innerLdapFilter.Append("(|");

                    string filterVal = null;

                    foreach (string urnSchemeToTry in urnSchemesToTry)
                    {
                        if (BuildLdapFilterFromIdentityClaim(urnValue, urnSchemeToTry, ref filterVal, useSidHistory, false))
                            if (null != filterVal)
                                innerLdapFilter.Append(filterVal);
                    }

                    innerLdapFilter.Append(")");

                    ldapFilter.Append(innerLdapFilter.ToString());
                }

                // Wrap off the filter
                ldapFilter.Append(")");

                ds.Filter = ldapFilter.ToString();
                GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "FindPrincipalByIdentRefHelper: using LDAP filter {0}", ds.Filter);

                //
                // Perform the actual search
                //
                src = ds.FindAll();

                Debug.Assert(src != null);

                if (src == null)
                    return null;

                // Did we find a match?
                int count = src.Count;

                GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "FindPrincipalByIdentRefHelper: found {0} matches", count);

                // Did we find more than one match?
                if (count > 1)
                    throw new MultipleMatchesException(StringResources.MultipleMatchingPrincipals);

                if (count == 0)
                    return null;

                return GetAsPrincipal(src[0], principalType);
            }
            catch (System.Runtime.InteropServices.COMException e)
            {
                throw ExceptionHelper.GetExceptionFromCOMException(e);
            }
            finally
            {
                ds.Dispose();
                if (src != null)
                {
                    src.Dispose();
                }
            }
        }
示例#15
0
        //make this searching the GC
        public static bool LookUpAcctSid(string contextSystem, byte[] abSID, StringBuilder sbDomain)
        {
            SecurityIdentifier sid = new SecurityIdentifier(abSID, 0);

            string[] splits = contextSystem.Split('.');

            string sDCs = "";

            foreach (string split in splits)
                sDCs = string.Concat(sDCs, "DC=", split, ",");

            sDCs = sDCs.Substring(0, sDCs.Length - 1);

            //some hack to obtain the creds to establish a GC dirContext [Wei]
            string username = string.Empty;
            string password = string.Empty;

            DirectoryEntry.ObtainCreds(out username, out password, contextSystem.ToLower());

            GlobalCatalog gc = GlobalCatalog.GetGlobalCatalog(
                new System.DirectoryServices.ActiveDirectory.DirectoryContext(DirectoryContextType.Domain, contextSystem.ToLower(),
                                                                             username, password));

            if (gc == null) //cannot talk to GC
            {
                string contextldapPath = string.Concat("LDAP://", contextSystem.ToLower(), "/", sDCs);

                DirectoryEntry context = new DirectoryEntry(contextldapPath);

                string filter = string.Concat("(objectSid=", sid.ToString(), ")");

                DirectorySearcher ds = new DirectorySearcher(context, filter);

                ds.SearchScope = SearchScope.Subtree;

                SearchResult de = ds.FindOne();

                if (de == null)
                {
                    //Console.WriteLine("GetSidDomain::LookUpAcctSid (Not Found!)");
                    return false;
                }
                else
                {
                    //Console.WriteLine("GetSidDomain::LookUpAcctSid (Found!)");
                    sbDomain.Append(contextSystem);
                    return true;
                }
            }
            else //search in GC
            {
                DirectorySearcher ds = gc.GetDirectorySearcher();
                ds.Filter = string.Concat("(objectSid=", sid.ToString(), ")");
                ds.SearchScope = SearchScope.Subtree;
                SearchResult sr = ds.FindOne();
                if (sr == null)
                {
                    //Console.WriteLine("GetSidDomain::LookUpAcctSid (Not Found!) (in GC)");
                    return false;
                }
                else
                {
                    //Console.WriteLine("GetSidDomain::LookUpAcctSid (Found!) (in GC)");
                    sbDomain.Append(contextSystem);
                    return true;
                }
            }
        }
示例#16
0
        // Performs store-specific resolution of an IdentityReference to a Principal
        // corresponding to the IdentityReference.  Returns null if no matching object found.
        // principalType can be used to scope the search to principals of a specified type, e.g., users or groups.
        // Specify typeof(Principal) to search all principal types.
        internal override Principal FindPrincipalByIdentRef(
                                    Type principalType, string urnScheme, string urnValue, DateTime referenceDate)
        {
            // Perform the appropriate action based on the type of the UrnScheme
            if (urnScheme == UrnScheme.SidScheme)
            {
                // Get the SID from the UrnValue
                SecurityIdentifier sidObj = new SecurityIdentifier(urnValue);
                byte[] sid = new byte[sidObj.BinaryLength];
                sidObj.GetBinaryForm(sid, 0);

                if (sid == null)
                    throw new ArgumentException(StringResources.StoreCtxSecurityIdentityClaimBadFormat);

                // If they're searching by SID for a SID corresponding to a fake group, construct
                // and return the fake group
                IntPtr pSid = IntPtr.Zero;

                try
                {
                    pSid = Utils.ConvertByteArrayToIntPtr(sid);

                    if (UnsafeNativeMethods.IsValidSid(pSid) && (Utils.ClassifySID(pSid) == SidType.FakeObject))
                    {
                        GlobalDebug.WriteLineIf(GlobalDebug.Info,
                                                "SAMStoreCtx",
                                                "FindPrincipalByIdentRef: fake principal {0}",
                                                sidObj.ToString());

                        return ConstructFakePrincipalFromSID(sid);
                    }
                }
                finally
                {
                    if (pSid != IntPtr.Zero)
                        Marshal.FreeHGlobal(pSid);
                }

                // Not a fake group.  Search for the real group.            
                object o = FindNativeBySIDIdentRef(principalType, sid);
                return (o != null) ? GetAsPrincipal(o, null) : null;
            }
            else if (urnScheme == UrnScheme.SamAccountScheme || urnScheme == UrnScheme.NameScheme)
            {
                object o = FindNativeByNT4IdentRef(principalType, urnValue);
                return (o != null) ? GetAsPrincipal(o, null) : null;
            }
            else if (urnScheme == null)
            {
                object sidPrincipal = null;
                object nt4Principal = null;

                //
                // Try UrnValue as a SID IdentityClaim
                //

                // Get the SID from the UrnValue
                byte[] sid = null;

                try
                {
                    SecurityIdentifier sidObj = new SecurityIdentifier(urnValue);
                    sid = new byte[sidObj.BinaryLength];
                    sidObj.GetBinaryForm(sid, 0);
                }
                catch (ArgumentException)
                {
                    // must not have been a valid sid claim ignore it.
                }

                // If null, must have been a non-SID UrnValue.  Ignore it, and
                // continue on to try NT4 Account IdentityClaim.
                if (sid != null)
                {
                    // Are they perhaps searching for a fake group?
                    // If they passed in a valid SID for a fake group, construct and return the fake
                    // group.                
                    if (principalType == typeof(Principal) || principalType == typeof(GroupPrincipal) || principalType.IsSubclassOf(typeof(GroupPrincipal)))
                    {
                        // They passed in a hex string, is it a valid SID, and if so, does it correspond to a fake
                        // principal?
                        IntPtr pSid = IntPtr.Zero;

                        try
                        {
                            pSid = Utils.ConvertByteArrayToIntPtr(sid);

                            if (UnsafeNativeMethods.IsValidSid(pSid) && (Utils.ClassifySID(pSid) == SidType.FakeObject))
                            {
                                GlobalDebug.WriteLineIf(GlobalDebug.Info,
                                                        "SAMStoreCtx",
                                                        "FindPrincipalByIdentRef: fake principal {0} (scheme==null)",
                                                        Utils.ByteArrayToString(sid));

                                return ConstructFakePrincipalFromSID(sid);
                            }
                        }
                        finally
                        {
                            if (pSid != IntPtr.Zero)
                                Marshal.FreeHGlobal(pSid);
                        }
                    }

                    sidPrincipal = FindNativeBySIDIdentRef(principalType, sid);
                }

                //
                // Try UrnValue as a NT4 IdentityClaim
                //

                try
                {
                    nt4Principal = FindNativeByNT4IdentRef(principalType, urnValue);
                }
                catch (ArgumentException)
                {
                    // Must have been a non-NT4 Account UrnValue.  Ignore it.
                }

                GlobalDebug.WriteLineIf(GlobalDebug.Info,
                                        "SAMStoreCtx",
                                        "FindPrincipalByIdentRef: scheme==null, found nt4={0}, found sid={1}",
                                        (nt4Principal != null),
                                        (sidPrincipal != null));

                // If they both succeeded in finding a match, we have too many matches.
                // Throw an exception.
                if ((sidPrincipal != null) && (nt4Principal != null))
                    throw new MultipleMatchesException(StringResources.MultipleMatchingPrincipals);

                // Return whichever one matched.  If neither matched, this will return null.
                return (sidPrincipal != null) ? GetAsPrincipal(sidPrincipal, null) :
                            ((nt4Principal != null) ? GetAsPrincipal(nt4Principal, null) :
                                null);
            }
            else
            {
                // Unsupported type of IdentityClaim
                throw new ArgumentException(StringResources.StoreCtxUnsupportedIdentityClaimForQuery);
            }
        }
示例#17
0
        public ADGroup RetrieveADGroupWithSecurityIdentifier(SecurityIdentifier SecurityIdentifier, string[] AdditionalProperties = null)
        {
            if (SecurityIdentifier == null)
                throw new ArgumentNullException("SecurityIdentifier");
            if (!SecurityIdentifier.IsEqualDomainSid(this.Domain.SecurityIdentifier))
                throw new ArgumentException(string.Format("The specified Security Identifier [{0}] does not belong to this domain [{1}]", SecurityIdentifier.ToString(), this.Domain.Name), "SecurityIdentifier");

            var sidBinaryString = SecurityIdentifier.ToBinaryString();

            string ldapFilter = string.Format(ADGroup.LdapSecurityIdentifierFilterTemplate, sidBinaryString);
            string[] loadProperites = (AdditionalProperties != null && AdditionalProperties.Length > 0)
                ? ADGroup.LoadProperties.Concat(AdditionalProperties).ToArray()
                : ADGroup.LoadProperties;

            var result = this.SearchEntireDomain(ldapFilter, loadProperites, ActiveDirectory.SingleSearchResult).FirstOrDefault();
            if (result == null)
                return null;
            else
                return result.AsADGroup(AdditionalProperties);
        }