Пример #1
0
        static DSNAME ParseObjectDsDn(string object_dn)
        {
            string pattern = @"<GUID=([a-fA-F0-9\-]+)>;(<SID=([a-fA-F0-9]+)>;)?(.*)";
            Regex  r       = new Regex(pattern);
            Match  m       = r.Match(object_dn);

            Guid   guid    = Guid.Empty;
            string guidStr = m.Groups[1].Value;

            if (guidStr.Contains("-"))
            {
                guid = new Guid(guidStr);
            }
            else
            {
                byte[] guidBinary = FromBinaryString(m.Groups[1].Value);
                guid = new Guid(guidBinary);
            }

            string dn     = m.Groups[4].Value;
            DSNAME dsName = DrsuapiClient.CreateDsName(dn, guid, null);

            string sidStr = m.Groups[3].Value;

            if (sidStr.Length > 0)
            {
                byte[]             sidBinary = FromBinaryString(sidStr);
                SecurityIdentifier secId     = new SecurityIdentifier(sidBinary, 0);
                dsName.SidLen = (uint)secId.BinaryLength;
                // Sid.Data is always 28 bytes long
                Array.Copy(sidBinary, dsName.Sid.Data, sidBinary.Length);
            }
            return(dsName);
        }
 string DomainNetBIOSNameFromDomain(DsServer dc, DSNAME domainNc)
 {
     return(((string)GetAttributeValue(
                 dc,
                 LdapUtility.ConvertUshortArrayToString(domainNc.StringName),
                 "name")).ToUpper());
 }
        static int CompareDsNames(DSNAME a, DSNAME b)
        {
            string na = LdapUtility.ConvertUshortArrayToString(a.StringName);
            string nb = LdapUtility.ConvertUshortArrayToString(b.StringName);

            return(na.CompareTo(nb));
        }
        string GetCanonicalName(DsServer dc, DSNAME obj, bool extended)
        {
            string result;
            string dn = LdapUtility.ConvertUshortArrayToString(obj.StringName);

            //if (GetObjectNC(dc, obj).Guid == obj.Guid)
            if (RetrieveDCSuffixFromDn(dn) == dn)
            {
                return(DomainDNSNameFromDomain(dc, obj));
            }


            DSNAME parentObj = GetDsName(dc, GetParentObjectDn(dn)).Value;

            result = GetCanonicalName(dc, parentObj, false);
            if (extended == true)
            {
                result = result + "\n";
            }
            else
            {
                result = result + "/";
            }

            string name = (string)GetAttributeValue(dc, dn, "name");

            result = result + name;
            return(result);
        }
Пример #5
0
        /// <summary>
        /// get the DSName of the specified NC.
        /// </summary>
        /// <param name="domain">Domain that contains the NC.</param>
        /// <param name="ncType">The naming context type.</param>
        /// <returns>The DSName of the specified NC. Null if the NC is not existed.</returns>
        public static DSNAME GetNamingContextDSName(DsDomain domain, NamingContext ncType)
        {
            DSNAME ncDsName = new DSNAME();

            if (ncType == NamingContext.ConfigNC)
            {
                ncDsName = domain.ConfigNC;
            }
            else if (ncType == NamingContext.SchemaNC)
            {
                ncDsName = domain.SchemaNC;
            }
            else if (ncType == NamingContext.DomainNC)
            {
                if (domain is AddsDomain)
                {
                    ncDsName = ((AddsDomain)domain).DomainNC;
                }
            }
            else
            {
                if (domain is AdldsDomain)
                {
                    ncDsName = ((AdldsDomain)domain).AppNCs[0];
                }
            }

            return(ncDsName);
        }
        public DSNAME GetObjectNC(DsServer dc, DSNAME obj)
        {
            RootDSE rootDse = LdapUtility.GetRootDSE(dc);

            string dn = LdapUtility.ConvertUshortArrayToString(obj.StringName);

            string ncDn = "";

            // there might be spaces between each RDN of the dn.
            dn = TrimDn(dn);

            // default first
            if (rootDse.defaultNamingContext != null)
            {
                // AD LDS doesn't have default NC
                if (dn.Contains(rootDse.defaultNamingContext))
                {
                    ncDn = rootDse.defaultNamingContext;
                }
            }

            if (dn.Contains(rootDse.configurationNamingContext))
            {
                ncDn = rootDse.configurationNamingContext;
            }

            if (dn.Contains(rootDse.schemaNamingContext))
            {
                ncDn = rootDse.schemaNamingContext;
            }

            return(LdapUtility.CreateDSNameForObject(dc, ncDn));
        }
        // <summary>
        // the function is used to create a DrsUpdateRef request
        // </summary>
        public DRS_MSG_UPDREFS CreateRequestForDrsUpdateRef(
            EnvironmentConfig.Machine machine,
            DsServer dest,
            DRS_OPTIONS options,
            NamingContext nc = NamingContext.ConfigNC)
        {
            string nc_name = null;
            Guid   nc_guid = Guid.Empty;
            string nc_sid  = null;
            DSNAME nc_obj;

            switch (nc)
            {
            case NamingContext.ConfigNC:
                nc_obj = dest.Domain.ConfigNC;
                break;

            case NamingContext.SchemaNC:
                nc_obj = dest.Domain.SchemaNC;
                break;

            case NamingContext.AppNC:
                if (EnvironmentConfig.TestDS)
                {
                    nc_obj = ((AddsDomain)dest.Domain).OtherNCs[0];
                }
                else
                {
                    nc_obj = ((AdldsDomain)dest.Domain).AppNCs[0];
                }
                break;

            case NamingContext.DomainNC:
                if (!EnvironmentConfig.TestDS)
                {
                    nc_obj = new DSNAME();
                }
                nc_obj = ((AddsDomain)dest.Domain).DomainNC;
                break;

            default:
                nc_obj = new DSNAME();
                break;
            }

            nc_name = LdapUtility.ConvertUshortArrayToString(nc_obj.StringName);
            nc_guid = nc_obj.Guid;
            nc_sid  = convertSidToString(nc_obj.Sid);

            DRS_MSG_UPDREFS?req = DRSClient.CreateUpdateRefsRequest(
                nc_name,
                nc_guid,
                nc_sid,
                dest.DsaNetworkAddress,
                dest.NtdsDsaObjectGuid,
                options);

            return((DRS_MSG_UPDREFS)req);
        }
        private void DRSReplicaSync_Invalid_Input_4(DrsReplicaSync_Versions dwInVersion)
        {
            uint ret = drsTestClient.DrsBind(
                EnvironmentConfig.Machine.WritableDC1,
                EnvironmentConfig.User.ParentDomainAdmin,
                DRS_EXTENSIONS_IN_FLAGS.DRS_EXT_BASE);
            /* comments from TD */

            /*
             *  if (DRS_SYNC_BYNAME in options and msgIn.pszDsaSrc = null)
             *      or (not DRS_SYNC_BYNAME in options and msgIn.uuidDsaSrc = null)
             *      or (not DRS_SYNC_BYNAME in options and msgIn.uuidDsaSrc = NULLGUID) then
             *    return ERROR_DS_DRA_INVALID_PARAMETER
             *  endif
             */

            /* Create request message */
            DRS_MSG_REPSYNC msgIn = new DRS_MSG_REPSYNC();
            // NC
            DsServer srv      = (DsServer)EnvironmentConfig.MachineStore[EnvironmentConfig.Machine.WritableDC1];
            RootDSE  rootDse  = LdapUtility.GetRootDSE(srv);
            DSNAME   ncDsname = LdapUtility.CreateDSNameForObject(srv, rootDse.configurationNamingContext);

            switch (dwInVersion)
            {
            case DrsReplicaSync_Versions.V1:
                msgIn = drsTestClient.CreateDrsReplicaSyncV1Request();
                /* Setting param #1 */
                msgIn.V1.ulOptions = 0;
                /* Setting param #2 */
                msgIn.V1.uuidDsaSrc = Guid.Empty;
                msgIn.V1.pNC        = ncDsname;
                break;

            case DrsReplicaSync_Versions.V2:
                msgIn = drsTestClient.CreateDrsReplicaSyncV2Request();
                /* Setting param #1 */
                msgIn.V2.ulOptions = 0;
                /* Setting param #2 */
                msgIn.V2.uuidDsaSrc = Guid.Empty;
                msgIn.V2.pNC        = ncDsname;
                break;

            default:
                BaseTestSite.Assert.Fail("The version {0} is not supported.", dwInVersion);
                break;
            }

            /* Issue the request */
            ret = drsTestClient.DRSClient.DrsReplicaSync(
                EnvironmentConfig.DrsContextStore[EnvironmentConfig.Machine.WritableDC1],
                (uint)dwInVersion,
                msgIn);
            BaseTestSite.Assert.AreEqual <uint>(
                (uint)Win32ErrorCode_32.ERROR_DS_DRA_INVALID_PARAMETER,
                ret,
                "DrsReplicaSync: return code mismatch."
                );
        }
        public void DRSR_DRSGetNCChanges_Access_Denied()
        {
            DrsrTestChecker.Check();
            uint ret = drsTestClient.DrsBind(
                EnvironmentConfig.Machine.WritableDC1,
                EnvironmentConfig.User.ParentDomainUser,
                DRS_EXTENSIONS_IN_FLAGS.DRS_EXT_BASE
                | DRS_EXTENSIONS_IN_FLAGS.DRS_EXT_GETCHGREPLY_V6);
            /* comments from TD */

            /*
             * if IsGetNCChangesPermissionGranted(msgIn) == FALSE then
             * return ERROR_DRA_ACCESS_DENIED
             * endif
             *
             */

            /* comments from likezh */

            /*
             * IsGetNCChangesPermissionGranted(msgIn) == FALSE
             */
            //throw new NotImplementedException();

            /* Create request message */
            DRS_MSG_GETCHGREQ msgIn = drsTestClient.CreateDrsGetNcChangesV8Request();

            uint dwInVersion  = 8;
            uint?dwOutVersion = 0;
            DRS_MSG_GETCHGREPLY?reply;
            /* Setting param #1 */
            /*msgIn.V8.pNC = DefaultNC()*/
            // NC
            DsServer srv = (DsServer)EnvironmentConfig.MachineStore[EnvironmentConfig.Machine.WritableDC1];

            RootDSE rootDse  = LdapUtility.GetRootDSE(srv);
            DSNAME  ncDsname = LdapUtility.CreateDSNameForObject(srv, rootDse.configurationNamingContext);

            msgIn.V8.pNC = ncDsname;
            if (EnvironmentConfig.TestDS == false)
            {
                // ADAM requires a DSA GUID
                msgIn.V8.uuidDsaObjDest = srv.NtdsDsaObjectGuid;
            }

            /* Issue the request */
            ret = drsTestClient.DRSClient.DrsGetNcChanges(
                EnvironmentConfig.DrsContextStore[EnvironmentConfig.Machine.WritableDC1],
                dwInVersion,
                msgIn,
                out dwOutVersion,
                out reply);
            BaseTestSite.Assert.AreEqual <uint>(
                (uint)Win32ErrorCode_32.ERROR_DS_DRA_ACCESS_DENIED,
                ret,
                "DrsGetNcChanges: return code mismatch."
                );
        }
        public void DRSR_DRSGetObjectExistence_Access_Denied()
        {
            DrsrTestChecker.Check();
            uint ret = drsTestClient.DrsBind(
                EnvironmentConfig.Machine.WritableDC1,
                EnvironmentConfig.User.ParentDomainUser,
                DRS_EXTENSIONS_IN_FLAGS.DRS_EXT_BASE);
            /* comments from TD */

            /*
             * if not AccessCheckCAR(nc, DS-Replication-Get-Changes) then
             * return ERROR_DS_DRA_ACCESS_DENIED
             * endif
             *
             */

            /* comments from likezh */

            /*
             * !AccessCheckCAR(nc, DS-Replication-Get-Changes)
             */
            //throw new NotImplementedException();

            /* Create request message */
            DRS_MSG_EXISTREQ msgIn = drsTestClient.CreateDrsGetObjectExistenceV1Request();

            // NC
            DsServer srv = (DsServer)EnvironmentConfig.MachineStore[EnvironmentConfig.Machine.WritableDC1];

            RootDSE rootDse  = LdapUtility.GetRootDSE(srv);
            DSNAME  ncDsname = LdapUtility.CreateDSNameForObject(srv, rootDse.defaultNamingContext);

            msgIn.V1.pNC = ncDsname;

            // This API will check the guidStart first to validate the input, so
            // to go thru that we set the guidStart to any guid.
            msgIn.V1.guidStart = DRSConstants.DrsRpcInterfaceGuid;

            uint dwInVersion  = 1;
            uint?dwOutVersion = 0;
            DRS_MSG_EXISTREPLY?reply;

            /* Issue the request */
            ret = drsTestClient.DRSClient.DrsGetObjectExistence(
                EnvironmentConfig.DrsContextStore[EnvironmentConfig.Machine.WritableDC1],
                dwInVersion,
                msgIn,
                out dwOutVersion,
                out reply);
            BaseTestSite.Assert.AreEqual <uint>(
                (uint)Win32ErrorCode_32.ERROR_DS_DRA_ACCESS_DENIED,
                ret,
                "DrsGetObjectExistence: return code mismatch."
                );
        }
        public void DRSR_DRSVerifyNames_Verify_Dsnames()
        {
            DrsrTestChecker.Check();
            // Init the data.
            EnvironmentConfig.Machine srv = EnvironmentConfig.Machine.WritableDC1;
            DsServer server = (DsServer)EnvironmentConfig.MachineStore[srv];

            uint ret = 0;

            ret = drsTestClient.DrsBind(
                srv,
                EnvironmentConfig.User.ParentDomainAdmin,
                DRS_EXTENSIONS_IN_FLAGS.DRS_EXT_BASE
                );

            BaseTestSite.Assert.AreEqual <uint>(0, ret,
                                                "IDL_DRSBind: Checking return value - got: {0}, expect: {1}, return value should always be 0 with a success bind to DC",
                                                ret, 0);

            // Create a DSNAME
            string dn     = server.Site.DN;
            DSNAME dsSite = ldapAdapter.GetDsName(server, dn).Value;

            // Prefix table
            SCHEMA_PREFIX_TABLE prefixTable = OIDUtility.CreatePrefixTable();

            // Create the attribute block. Here we go to RDN attribute.
            string rdnAttrId = DRSConstants.RDN_OID;
            uint   attrTyp   = OIDUtility.MakeAttid(prefixTable, rdnAttrId);

            ATTRVAL      attrVal      = DrsuapiClient.CreateATTRVAL(null);
            ATTRVALBLOCK attrValBlock = DrsuapiClient.CreateATTRVALBLOCK(new ATTRVAL[] { attrVal });
            ATTR         attr         = DrsuapiClient.CreateATTR(attrTyp, attrValBlock);
            ATTRBLOCK    attrBlock    = DrsuapiClient.CreateATTRBLOCK(new ATTR[] { attr });

            // Actual RPC call.
            ret = drsTestClient.DrsVerifyNames(
                srv,
                dwInVersion_Values.V1,
                DRS_MSG_VERIFYREQ_V1_dwFlags_Values.DRS_VERIFY_DSNAMES,
                new DSNAME[] { dsSite },
                new string[] { dn },
                attrBlock,
                prefixTable
                );

            BaseTestSite.Assert.AreEqual <uint>(0, ret,
                                                "IDL_DRSVerifyNames: Checking return value - got: {0}, expect: {1}, return value should always be 0",
                                                ret, 0);
            // Unbind
            ret = drsTestClient.DrsUnbind(srv);
            BaseTestSite.Assert.AreEqual <uint>(0, ret,
                                                "IDL_DRSUnbind: Checking return value - got: {0}, expect: {1}, return value should always be 0",
                                                ret, 0);
        }
        public void DRSR_DRSReplicaSync_Invalid_Input_2()
        {
            DrsrTestChecker.Check();
            uint ret = drsTestClient.DrsBind(
                EnvironmentConfig.Machine.WritableDC1,
                EnvironmentConfig.User.ParentDomainAdmin,
                DRS_EXTENSIONS_IN_FLAGS.DRS_EXT_BASE);
            /* comments from TD */

            /*
             * options := msgIn.ulOptions
             * if msgIn.pNC = null
             * or (not DRS_SYNC_ALL in options
             * and msgIn.uuidDsaSrc = null
             * and msgIn.pszDsaSrc = null) then
             * return ERROR_DS_DRA_INVALID_PARAMETER
             * endif
             *
             */


            /* Create request message */
            DRS_MSG_REPSYNC msgIn = drsTestClient.CreateDrsReplicaSyncV1Request();

            uint dwInVersion = 1;

            /* Setting param #1 */
            /*msgIn.V1.ulOptions = 0*/
            msgIn.V1.ulOptions = 0;
            /* Setting param #2 */
            /*msgIn.V1.uuidDsaSrc = Guid.Empty*/
            msgIn.V1.uuidDsaSrc = Guid.Empty;
            /* Setting param #3 */
            /*msgIn.V1.pszDsaSrc = null*/
            msgIn.V1.pszDsaSrc = null;
            // NC
            DsServer srv = (DsServer)EnvironmentConfig.MachineStore[EnvironmentConfig.Machine.WritableDC1];

            RootDSE rootDse  = LdapUtility.GetRootDSE(srv);
            DSNAME  ncDsname = LdapUtility.CreateDSNameForObject(srv, rootDse.configurationNamingContext);

            msgIn.V1.pNC = ncDsname;

            /* Issue the request */
            ret = drsTestClient.DRSClient.DrsReplicaSync(
                EnvironmentConfig.DrsContextStore[EnvironmentConfig.Machine.WritableDC1],
                dwInVersion,
                msgIn);
            BaseTestSite.Assert.AreEqual <uint>(
                (uint)Win32ErrorCode_32.ERROR_DS_DRA_INVALID_PARAMETER,
                ret,
                "DrsReplicaSync: return code mismatch."
                );
        }
        public void DRSR_DRSReplicaSync_No_Replica()
        {
            DrsrTestChecker.Check();
            uint ret = drsTestClient.DrsBind(
                EnvironmentConfig.Machine.WritableDC1,
                EnvironmentConfig.User.ParentDomainAdmin,
                DRS_EXTENSIONS_IN_FLAGS.DRS_EXT_BASE);
            /* comments from TD */

            /*
             * rf := select all v in nc!repsFrom
             * where DRS_SYNC_ALL in options
             * or (DRS_SYNC_BYNAME in options
             *  and v.naDsa = msgIn.pszDsaSrc)
             * or (not DRS_SYNC_BYNAME in options
             *  and v.uuidDsa = msgIn.uuidDsaSrc)
             * if rf = null then
             * return ERROR_DS_DRA_NO_REPLICA
             * endif
             *
             */


            /* Create request message */
            DRS_MSG_REPSYNC msgIn = drsTestClient.CreateDrsReplicaSyncV1Request();

            uint dwInVersion = 1;

            /* Setting param #1 */
            /*msgIn.V1.pszDsaSrc = "InvalidDsaSrc"*/
            msgIn.V1.pszDsaSrc = "InvalidDsaSrc";
            /* Setting param #2 */
            /*msgIn.V1.ulOptions = (uint)DRS_OPTIONS.DRS_SYNC_BYNAME*/
            msgIn.V1.ulOptions = (uint)DRS_OPTIONS.DRS_SYNC_BYNAME;

            // NC
            DsServer srv = (DsServer)EnvironmentConfig.MachineStore[EnvironmentConfig.Machine.WritableDC1];

            RootDSE rootDse  = LdapUtility.GetRootDSE(srv);
            DSNAME  ncDsname = LdapUtility.CreateDSNameForObject(srv, rootDse.defaultNamingContext);

            msgIn.V1.pNC = ncDsname;

            /* Issue the request */
            ret = drsTestClient.DRSClient.DrsReplicaSync(
                EnvironmentConfig.DrsContextStore[EnvironmentConfig.Machine.WritableDC1],
                dwInVersion,
                msgIn);
            BaseTestSite.Assert.AreEqual <uint>(
                (uint)Win32ErrorCode_32.ERROR_DS_DRA_NO_REPLICA,
                ret,
                "DrsReplicaSync: return code mismatch."
                );
        }
        DSNAME?DescendantObject(DsServer dc, string ancestor, string rdns)
        {
            string dn = rdns + ancestor;
            DSNAME ds = LdapUtility.CreateDSNameForObject(dc, dn);

            if (ds.StringName == null)
            {
                return(null);
            }

            return(ds);
        }
        DSNAME[] LookupSPN(DsServer dc, uint flags, string name)
        {
            DSNAME[] rt     = null;
            Guid?    dcGuid = null;

            string[] spnMappings = null;
            string   mappedSpn   = null;

            RootDSE rootDse = LdapUtility.GetRootDSE(dc);

            rt = LookupAttr(dc, flags, "servicePrincipalName", name);
            if (rt != null)
            {
                return(rt);
            }

            string dsService = "CN=Directory Service,CN=Windows NT,CN=Services," + rootDse.configurationNamingContext;

            spnMappings = LdapUtility.GetAttributeValuesString(dc, dsService + rootDse.configurationNamingContext, "sPNMappings");
            if (spnMappings != null)
            {
                mappedSpn = MapSPN(name, spnMappings);
                if (mappedSpn != null)
                {
                    rt = LookupAttr(dc, flags, "servicePrincipalName", mappedSpn);
                    if (rt != null)
                    {
                        return(rt);
                    }
                }
            }

            if (GetServiceClassFromSPN(name) == DrsrUtility.DRSUAPI_RPC_INTERFACE_UUID.ToString().ToUpper() &&
                GetServiceNameFromSPN(name) == DomainNameFromDN(rootDse.defaultNamingContext))
            {
                dcGuid = new Guid(GetInstanceNameFromSPN(name));
                if (dcGuid != null)
                {
                    string objDn = LdapUtility.GetObjectDnByGuid(dc, rootDse.configurationNamingContext, dcGuid.Value);
                    if (objDn != null)
                    {
                        objDn = GetParentObjectDn(objDn);
                        if (objDn != null)
                        {
                            string srvRef = (string)GetAttributeValue(dc, objDn, "serverReference");
                            rt = new DSNAME[] { GetDsName(dc, srvRef).Value };
                        }
                    }
                }
            }

            return(rt);
        }
        public DSNAME[] GetMemberships(
            DsServer dc,
            DSNAME names,
            REVERSE_MEMBERSHIP_OPERATION_TYPE operationType,
            DSNAME?limitingDomain)
        {
            string baseDn = LdapUtility.ConvertUshortArrayToString(
                ((AddsDomain)dc.Domain).DomainNC.StringName
                );

            string        name    = LdapUtility.ConvertUshortArrayToString(names.StringName);
            List <DSNAME> results = new List <DSNAME>();

            // GroupMembersTransitive
            if (operationType == REVERSE_MEMBERSHIP_OPERATION_TYPE.GroupMembersTransitive)
            {
                return(GetGroupMembersTransitive(dc, names));
            }

            // Get the primary group first
            DSNAME primaryGroup = LdapUtility.GetPrimaryGroup(dc, name, baseDn).Value;
            uint   groupType    = (uint)Convert.ToInt32(
                (string)LdapUtility.GetAttributeValue(
                    dc,
                    LdapUtility.ConvertUshortArrayToString(primaryGroup.StringName),
                    "groupType")
                );

            if (FilterGroupOperationType(operationType, groupType))
            {
                // Valid primary group
                results.Add(primaryGroup);
            }


            string[] memberOfs = LdapUtility.GetAttributeValuesString(dc, name, "memberOf");
            foreach (string grpName in memberOfs)
            {
                // Get groupType and filter using the filters
                groupType = (uint)Convert.ToInt32(
                    LdapUtility.GetAttributeValue(dc, grpName, "groupType")
                    );

                if (!FilterGroupOperationType(operationType, groupType))
                {
                    continue;
                }

                results.Add(LdapUtility.CreateDSNameForObject(dc, grpName));
            }
            return(results.ToArray());
        }
Пример #17
0
        public void DRSR_DRSGetMemberships_Get_Global_Groups_Non_Transitive()
        {
            DrsrTestChecker.Check();
            // Init the data.
            EnvironmentConfig.Machine srv = EnvironmentConfig.Machine.WritableDC1;
            DsServer server = (DsServer)EnvironmentConfig.MachineStore[srv];
            DsUser   user   = EnvironmentConfig.UserStore[EnvironmentConfig.User.ParentDomainAdmin];

            uint ret = 0;

            ret = drsTestClient.DrsBind(
                srv,
                EnvironmentConfig.User.ParentDomainAdmin,
                DRS_EXTENSIONS_IN_FLAGS.DRS_EXT_BASE
                );

            BaseTestSite.Assert.AreEqual <uint>(
                0,
                ret,
                "IDL_DRSBind: should return 0 with a success bind to DC");

            DSNAME dsUser = ldapAdapter.GetDsName(
                server,
                ldapAdapter.GetUserDn(
                    server,
                    user
                    )
                ).Value;

            ret = drsTestClient.DrsGetMemberships(
                srv,
                dwInVersion_Values.V1,
                dsUser,
                false,
                REVERSE_MEMBERSHIP_OPERATION_TYPE.RevMembGlobalGroupsNonTransitive,
                ((AddsDomain)(server.Domain)).DomainNC);

            BaseTestSite.Assert.AreEqual <uint>(
                0,
                ret,
                "IDL_DRSGetMemberships: return value should be 0");

            // Unbind
            ret = drsTestClient.DrsUnbind(srv);
            BaseTestSite.Assert.AreEqual <uint>(
                0,
                ret,
                "IDL_DRSUnbind: return value should be 0");
        }
Пример #18
0
        public void DRSR_DRSGetMemberships_Get_Group_Members_Transitive()
        {
            DrsrTestChecker.Check();

            // Init the data.
            EnvironmentConfig.Machine srv = EnvironmentConfig.Machine.WritableDC1;
            DsServer server = (DsServer)EnvironmentConfig.MachineStore[srv];
            DsUser   user   = EnvironmentConfig.UserStore[EnvironmentConfig.User.ParentDomainAdmin];

            uint ret = 0;

            ret = drsTestClient.DrsBind(
                srv,
                EnvironmentConfig.User.ParentDomainAdmin,
                DRS_EXTENSIONS_IN_FLAGS.DRS_EXT_BASE
                );

            BaseTestSite.Assert.AreEqual <uint>(
                0,
                ret,
                "IDL_DRSBind: should return 0 with a success bind to DC");
            string groupDn = "CN=Domain Users,CN=Users," + DrsrHelper.GetDNFromFQDN(ADCommonServerAdapter.Instance(Site).PrimaryDomainDnsName);
            DSNAME dsGroup = LdapUtility.CreateDSNameForObject(
                server,
                groupDn
                );

            ret = drsTestClient.DrsGetMemberships(
                srv,
                dwInVersion_Values.V1,
                dsGroup,
                false,
                REVERSE_MEMBERSHIP_OPERATION_TYPE.GroupMembersTransitive,
                null);

            BaseTestSite.Assert.AreEqual <uint>(
                0,
                ret,
                "IDL_DRSGetMemberships: return value should be 0");

            // Unbind
            ret = drsTestClient.DrsUnbind(srv);
            BaseTestSite.Assert.AreEqual <uint>(
                0,
                ret,
                "IDL_DRSUnbind: return value should be 0");
        }
        DirectoryAttribute GetAttrVals(
            DsServer dc,
            DSNAME o,
            string attrName,
            bool includeDeletedLinks = false)
        {
            SearchResultEntryCollection results = null;
            ResultCode re = Search(
                dc,
                LdapUtility.ConvertUshortArrayToString(o.StringName),
                "(objectClass=*)",
                System.DirectoryServices.Protocols.SearchScope.Base,
                new string[] { attrName },
                out results);

            if (re == ResultCode.Success)
            {
                return(results[0].Attributes[attrName]);
            }

            return(null);
        }
        private void DRSReplicaSync_Access_Denied(DrsReplicaSync_Versions dwInVersion)
        {
            uint ret = drsTestClient.DrsBind(
                EnvironmentConfig.Machine.WritableDC1,
                EnvironmentConfig.User.ParentDomainUser,
                DRS_EXTENSIONS_IN_FLAGS.DRS_EXT_BASE);
            /* comments from TD */

            /*
             *  if AccessCheckCAR(nc, DS-Replication-Synchronize) then
             *    return ERROR_DS_DRA_ACCESS_DENIED
             *  endif
             */

            /* comments from likezh */

            /*
             * !AccessCheckCAR(nc, DS-Replication-Synchronize)
             */
            //throw new NotImplementedException();

            /* Create request message */
            DRS_MSG_REPSYNC msgIn = new DRS_MSG_REPSYNC();
            // NC
            DsServer srv      = (DsServer)EnvironmentConfig.MachineStore[EnvironmentConfig.Machine.WritableDC1];
            RootDSE  rootDse  = LdapUtility.GetRootDSE(srv);
            DSNAME   ncDsname = LdapUtility.CreateDSNameForObject(srv, rootDse.defaultNamingContext);

            switch (dwInVersion)
            {
            case DrsReplicaSync_Versions.V1:
                msgIn        = drsTestClient.CreateDrsReplicaSyncV1Request();
                msgIn.V1.pNC = ncDsname;
                // This API will check the uuidDsaSrc first to validate the input, so
                // to go thru that we set the uuidDsaSrc to any guid.
                msgIn.V1.uuidDsaSrc = DRSConstants.DrsRpcInterfaceGuid;
                break;

            case DrsReplicaSync_Versions.V2:
                msgIn        = drsTestClient.CreateDrsReplicaSyncV2Request();
                msgIn.V2.pNC = ncDsname;
                // This API will check the uuidDsaSrc first to validate the input, so
                // to go thru that we set the uuidDsaSrc to any guid.
                msgIn.V2.uuidDsaSrc = DRSConstants.DrsRpcInterfaceGuid;
                break;

            default:
                BaseTestSite.Assert.Fail("The version {0} is not supported.", dwInVersion);
                break;
            }

            /* Issue the request */
            ret = drsTestClient.DRSClient.DrsReplicaSync(
                EnvironmentConfig.DrsContextStore[EnvironmentConfig.Machine.WritableDC1],
                (uint)dwInVersion,
                msgIn);
            BaseTestSite.Assert.AreEqual <uint>(
                (uint)Win32ErrorCode_32.ERROR_DS_DRA_ACCESS_DENIED,
                ret,
                "DrsReplicaSync: return code mismatch."
                );
        }
        /// <summary>
        /// load all infos
        /// </summary>
        /// <param name="site">PTD test site</param>
        public static void Initialize(ITestSite site)
        {
            if (site == null)
            {
                throw new ApplicationException("TestSite could not be NULL.");
            }

            //only initialize once
            if (dataLoaded)
            {
                if (!init_succeed)
                {
                    site.Assert.Fail("EnvironmentConfig init failed in previous cases");
                }
                return;
            }

            //try
            //{
            testSite        = site;
            ldapAd          = site.GetAdapter <ILdapAdapter>();
            ldapAd.Site     = site;
            testDS          = bool.Parse(site.Properties["MS_DRSR.TestDS"]);
            funcLv          = (Microsoft.Protocols.TestTools.StackSdk.ActiveDirectory.Drsr.DrsrDomainFunctionLevel)(ADCommonServerAdapter.Instance(testSite).DomainFunctionLevel);
            UseKerberos     = bool.Parse(site.Properties["MS_DRSR.UseKerberos"]);
            UseNativeRpcLib = bool.Parse(site.Properties["MS_DRSR.UseNativeRpcLib"]);

            //create normal user account if it does not exist yet
            string serverName   = ADCommonServerAdapter.Instance(testSite).PDCNetbiosName;
            string serverPort   = ADCommonServerAdapter.Instance(testSite).ADDSPortNum;
            string domainNC     = "DC=" + ADCommonServerAdapter.Instance(testSite).PrimaryDomainDnsName.Replace(".", ",DC=");
            string parentDN     = string.Format("CN=Users,{0}", domainNC);
            string userDN       = string.Format("CN={0},CN=Users,{1}", DomainUserName, domainNC);
            string userPassword = ADCommonServerAdapter.Instance(testSite).DomainUserPassword;

            if (!Utilities.IsObjectExist(userDN, serverName, serverPort))
            {
                Utilities.NewUser(serverName, serverPort, parentDN, DomainUserName, userPassword);
            }

            //please do all object intialization in this call following example
            InitUserObjects();
            InitDomainObjects();
            InitMachineObjects();
            FinishUserObjects();

            //load DS AppNC late due to rootDSE search issue
            if (testDS && !string.IsNullOrEmpty(AppNCDistinguishedName))
            {
                ((AddsDomain)DomainStore[DomainEnum.PrimaryDomain]).OtherNCs    = new DSNAME[1];
                ((AddsDomain)DomainStore[DomainEnum.PrimaryDomain]).OtherNCs[0] = ldapAd.GetDsName((DsServer)MachineStore[Machine.WritableDC1], AppNCDistinguishedName).Value;
            }

            MainDC = (AddsServer)EnvironmentConfig.MachineStore[Machine.MainDC];
            DsServer s1 = (DsServer)EnvironmentConfig.MachineStore[Machine.WritableDC1];

            transport_obj = ldapAd.GetDsName(
                s1,
                "cn=ip,cn=inter-site transports,cn=sites,"
                + LdapUtility.ConvertUshortArrayToString(s1.Domain.ConfigNC.StringName)
                ).Value;

            DsUser dcAccount = new DsUser();

            dcAccount.Domain   = s1.Domain;
            dcAccount.Username = s1.NetbiosName + "$";
            dcAccount.Password = ADCommonServerAdapter.Instance(testSite).PDCPassword;
            UserStore.Add(User.MainDCAccount, dcAccount);

            //not always need dc2
            if (EnvironmentConfig.MachineStore.ContainsKey(Machine.WritableDC2))
            {
                DsServer s2 = (DsServer)EnvironmentConfig.MachineStore[Machine.WritableDC2];

                DsUser dcAccount2 = new DsUser();
                dcAccount2.Domain   = s2.Domain;
                dcAccount2.Username = s2.NetbiosName + "$";
                dcAccount2.Password = ADCommonServerAdapter.Instance(testSite).SDCPassword;
                UserStore.Add(User.WritableDC2Account, dcAccount2);
            }

            if (EnvironmentConfig.MachineStore.ContainsKey(Machine.RODC))
            {
                DsServer rodc = (DsServer)EnvironmentConfig.MachineStore[Machine.RODC];

                DsUser rodcAccount = new DsUser();
                rodcAccount.Domain   = rodc.Domain;
                rodcAccount.Username = rodc.NetbiosName + "$";
                rodcAccount.Password = ADCommonServerAdapter.Instance(testSite).RODCPassword;
                UserStore.Add(User.RODCMachineAccount, rodcAccount);
            }
            //}
            //catch (Exception e)
            //{
            //    init_succeed = false;
            //    site.Assert.Fail("data initialization failed due to exception:" + e.InnerException == null ? e.Message : e.InnerException.Message);
            //}

            //alwasy only init once
            dataLoaded = true;
        }
        string[] ConstructOutput(DsServer dc, DSNAME obj, uint formatDesired)
        {
            string dn = LdapUtility.ConvertUshortArrayToString(obj.StringName);

            if (dn == null)
            {
                return(null);
            }

            string value = null;

            switch (formatDesired)
            {
            case (uint)DS_NAME_FORMAT.DS_FQDN_1779_NAME:
                value = (string)GetAttributeValue(dc, dn, "distinguishedName");
                break;

            case (uint)DS_NAME_FORMAT.DS_NT4_ACCOUNT_NAME:
                value = DomainNetBIOSNameFromDomain(dc, GetObjectNC(dc, obj)) + "\\" +
                        (string)GetAttributeValue(dc, dn, "sAMAccountName");
                break;

            case (uint)DS_NAME_FORMAT.DS_USER_PRINCIPAL_NAME:
                value = (string)GetAttributeValue(dc, dn, "userPrincipalName");
                break;

            case (uint)DS_NAME_FORMAT.DS_CANONICAL_NAME:
                value = GetCanonicalName(dc, obj, false);
                break;

            case (uint)DS_NAME_FORMAT.DS_UNIQUE_ID_NAME:
                // curly-braced form.
                value = "{"
                        + (new Guid((byte[])GetAttributeValue(dc, dn, "objectGuid"))).ToString()
                        + "}";
                break;

            case (uint)DS_NAME_FORMAT.DS_DISPLAY_NAME:
                value = (string)GetAttributeValue(dc, dn, "displayName");
                break;

            case (uint)DS_NAME_FORMAT.DS_SERVICE_PRINCIPAL_NAME:
                return(LdapUtility.GetAttributeValuesString(dc, dn, "servicePrincipalName"));

            case (uint)DS_NAME_FORMAT.DS_CANONICAL_NAME_EX:
                value = GetCanonicalName(dc, obj, true);
                break;

            case (uint)formatDesired_Values.DS_STRING_SID_NAME:
                value = LdapUtility.GetObjectStringSid(dc, dn);
                break;

            case (uint)formatDesired_Values.DS_USER_PRINCIPAL_NAME_FOR_LOGON:
            {
                string upn = (string)GetAttributeValue(dc, dn, "userPrincipalName");
                if (upn != null)
                {
                    value = upn;
                }
                else
                {
                    value = (string)GetAttributeValue(dc, dn, "sAMAccountName") + "@"
                            + DomainNetBIOSNameFromDomain(dc, GetObjectNC(dc, obj));
                }
            }
            break;

            default:
                break;
            }

            if (value != null)
            {
                return new string[] { value }
            }
            ;
            return(null);
        }

        DS_NAME_RESULT_ITEMW LookupFPO(bool fCanonicalEx, DSNAME obj, DS_NAME_RESULT_ITEMW result)
        {
            throw new NotImplementedException();
        }
Пример #23
0
        public static ATTRVAL ATTRVALFromValue(DsServer dc, string v, string attrSyntax, SCHEMA_PREFIX_TABLE prefixTable)
        {
            ATTRVAL attrVal = new ATTRVAL();

            switch (attrSyntax)
            {
            case "2.2.5.8":     // Boolean
            {
                attrVal.valLen = 4;
                attrVal.pVal   = new byte[4];
                if (v == "TRUE")
                {
                    attrVal.pVal[0] = 1;
                }
                else
                {
                    attrVal.pVal[0] = 0;
                }
                break;
            }

            case "2.5.5.9":     // Enumeration, Integer
            {
                attrVal.valLen = 4;
                int intValue = Convert.ToInt32(v);
                attrVal.pVal = BitConverter.GetBytes(intValue);
                break;
            }

            case "2.5.5.16":        // LargeInteger
            {
                attrVal.valLen = 8;
                long intValue = Convert.ToInt64(v);
                attrVal.pVal = BitConverter.GetBytes(intValue);
                break;
            }

            case "2.5.5.13":        // Object (Presentation-Address)
            {
                System.Text.UnicodeEncoding utf16 = new System.Text.UnicodeEncoding();
                byte[] data = utf16.GetBytes(v);

                attrVal.valLen = (uint)data.Length + 4;
                attrVal.pVal   = new byte[attrVal.valLen];

                byte[] intBytes = BitConverter.GetBytes(attrVal.valLen);

                Array.Copy(intBytes, 0, attrVal.pVal, 0, intBytes.Length);
                Array.Copy(data, 0, attrVal.pVal, intBytes.Length, data.Length);

                break;
            }

            case "2.5.5.4":        // String (Teletex)
            case "2.5.5.5":        // String (IA5), String (Printable)
            case "2.5.5.6":        // String (Numeric)
            case "2.5.5.10":       // Object (Replica-Link), string (Octet)
            {
                attrVal.pVal   = ToBinary(v);
                attrVal.valLen = (uint)attrVal.pVal.Length;
                break;
            }

            case "2.5.5.2":         // String (Object-Identifier)
            {
                if (v is string && v.Contains(".") == false)
                {
                    // Look in the Schema NC for the object class and it's governsID.
                    RootDSE rootDse  = LdapUtility.GetRootDSE(dc);
                    string  schemaNc = rootDse.schemaNamingContext;

                    v = LdapUtility.GetAttributeValueInString(
                        dc,
                        schemaNc,
                        "governsId",
                        "(&(objectClass=classSchema)(lDAPDisplayName=" + v + "))",
                        System.DirectoryServices.Protocols.SearchScope.Subtree);
                }

                attrVal.valLen = 4;
                uint attid = MakeAttid(prefixTable, v);
                attrVal.pVal = BitConverter.GetBytes(attid);
                break;
            }

            case "2.5.5.12":        // String (Unicode)
            {
                System.Text.UnicodeEncoding utf16 = new System.Text.UnicodeEncoding();
                attrVal.pVal   = utf16.GetBytes(v);
                attrVal.valLen = (uint)attrVal.pVal.Length;
                break;
            }

            case "2.5.5.11":        // String (UTC-Time), String (Generalized-Time)
            {
                DateTime t;
                string   timePattern = "yyyyMMddHHmmss.'0Z'";
                DateTime.TryParseExact(
                    v,
                    timePattern,
                    null,
                    System.Globalization.DateTimeStyles.None,
                    out t);

                DateTime dsTime = new DateTime(1601, 1, 1, 0, 0, 0);
                TimeSpan diff   = t - dsTime;
                attrVal.valLen = 8;
                attrVal.pVal   = BitConverter.GetBytes((ulong)diff.TotalSeconds);

                break;
            }

            case "2.5.5.1":         // Object (DS-DN)
            {
                DSNAME dsName = ParseObjectDsDn(v);

                attrVal.pVal   = TypeMarshal.ToBytes <DSNAME>(dsName);
                attrVal.valLen = (uint)attrVal.pVal.Length;
            }
            break;

            case "2.5.5.14":        // Object (DN-String), Object (Access-Point)
            {
                string pattern = @"S:([0-9a-fA-F]+):(.*):(.*)";
                Regex  r       = new Regex(pattern);
                Match  m       = r.Match(v);

                uint char_count = (uint)Convert.ToInt32(m.Groups[1].Value, 16);

                SYNTAX_ADDRESS sa = new SYNTAX_ADDRESS();
                sa.dataLen = (2 * char_count) + 4;

                System.Text.UnicodeEncoding utf16 = new System.Text.UnicodeEncoding();

                sa.byteVal = utf16.GetBytes(m.Groups[2].Value);
                byte[] saBin = TypeMarshal.ToBytes <SYNTAX_ADDRESS>(sa);

                DSNAME dsdn    = ParseObjectDsDn(m.Groups[3].Value);
                byte[] dsdnBin = TypeMarshal.ToBytes <DSNAME>(dsdn);

                // Add padding
                uint p = 4 - dsdn.structLen % 4;
                if (p == 4)
                {
                    p = 0;
                }
                byte[] padding = new byte[p];

                attrVal.pVal = new byte[dsdnBin.Length + p + saBin.Length];
                Array.Copy(dsdnBin, attrVal.pVal, dsdnBin.Length);
                Array.Copy(saBin, 0, attrVal.pVal, dsdnBin.Length + p, saBin.Length);

                attrVal.valLen = (uint)attrVal.pVal.Length;
            }
            break;

            case "2.5.5.7":         // Object (DN-Binary), Object (OR-Name)
            {
                string pattern = @"B:([0-9a-fA-F]+):([0-9a-fA-F]+):(.*)";
                Regex  r       = new Regex(pattern);
                Match  m       = r.Match(v);

                uint char_count = (uint)Convert.ToInt32(m.Groups[1].Value, 16);

                SYNTAX_ADDRESS sa = new SYNTAX_ADDRESS();
                sa.dataLen = char_count;
                sa.byteVal = FromBinaryString(m.Groups[2].Value);
                byte[] saBin = TypeMarshal.ToBytes <SYNTAX_ADDRESS>(sa);

                DSNAME dsdn    = ParseObjectDsDn(m.Groups[3].Value);
                byte[] dsdnBin = TypeMarshal.ToBytes <DSNAME>(dsdn);

                // Add padding
                uint p = 4 - dsdn.structLen % 4;
                if (p == 4)
                {
                    p = 0;
                }
                byte[] padding = new byte[p];

                attrVal.pVal = new byte[dsdnBin.Length + p + saBin.Length];
                Array.Copy(dsdnBin, attrVal.pVal, dsdnBin.Length);
                Array.Copy(saBin, 0, attrVal.pVal, dsdnBin.Length + p, saBin.Length);

                attrVal.valLen = (uint)attrVal.pVal.Length;
            }
            break;

            case "2.5.5.15":        // String (NT-Sec-Desc)
            case "2.5.5.17":        // String (SID)
            {
                attrVal.pVal   = FromBinaryString(v);
                attrVal.valLen = (uint)attrVal.pVal.Length;
            }
            break;

            default:
                break;
            }
            return(attrVal);
        }
        public DSNAME[] GetGroupMembersTransitive(
            DsServer dc,
            DSNAME name)
        {
            string baseDn = LdapUtility.ConvertUshortArrayToString(
                ((AddsDomain)dc.Domain).DomainNC.StringName
                );

            List <DSNAME> names = new List <DSNAME>();

            // primary groups
            uint pgId = 0;

            for (int i = 0; i < 4; ++i)
            {
                pgId <<= 8;
                pgId  += name.Sid.Data[name.SidLen - i - 1];
            }

            SearchResultEntryCollection results = null;
            DirectoryControlCollection  cc      = new DirectoryControlCollection();

            cc.Add(new SearchOptionsControl(SearchOption.DomainScope));
            ResultCode r = ControlledSearch(
                dc,
                baseDn,
                "(primaryGroupId=" + pgId.ToString() + ")",
                System.DirectoryServices.Protocols.SearchScope.Subtree,
                null,
                cc,
                out results);

            if (r == ResultCode.Success)
            {
                foreach (SearchResultEntry e in results)
                {
                    string obj = e.DistinguishedName;
                    names.Add(LdapUtility.CreateDSNameForObject(dc, obj));
                }
            }

            string[] members = LdapUtility.GetAttributeValuesString(
                dc,
                LdapUtility.ConvertUshortArrayToString(name.StringName),
                "member");

            if (members != null)
            {
                foreach (string m in members)
                {
                    names.Add(LdapUtility.CreateDSNameForObject(dc, m));
                }
            }

            if (names.Count > 0)
            {
                List <DSNAME> tn = new List <DSNAME>();
                foreach (DSNAME n in names)
                {
                    // Recursively find all members of the member.
                    DSNAME[] ns = GetGroupMembersTransitive(dc, n);
                    if (ns != null)
                    {
                        tn.AddRange(ns);
                    }
                }
                if (tn.Count > 0)
                {
                    names.AddRange(tn);
                }

                // Remove duplicates
                Comparison <DSNAME> cmp = new Comparison <DSNAME>(CompareDsNames);
                names.Sort(cmp);

                int i = 0;
                while (i < names.Count - 1)
                {
                    string na = LdapUtility.ConvertUshortArrayToString(names[i].StringName);
                    string nb = LdapUtility.ConvertUshortArrayToString(names[i + 1].StringName);
                    if (na == nb)
                    {
                        names.RemoveAt(i);
                    }
                    else
                    {
                        ++i;
                    }
                }
                return(names.ToArray());
            }

            return(null);
        }
        public void DRSR_DRSVerifyNames_Verify_SAM_Account_Names()
        {
            DrsrTestChecker.Check();
            // Init the data.
            EnvironmentConfig.Machine srv = EnvironmentConfig.Machine.WritableDC1;
            DsServer server = (DsServer)EnvironmentConfig.MachineStore[srv];
            DsUser   user   = EnvironmentConfig.UserStore[EnvironmentConfig.User.ParentDomainAdmin];

            uint ret = 0;

            ret = drsTestClient.DrsBind(
                srv,
                EnvironmentConfig.User.ParentDomainAdmin,
                DRS_EXTENSIONS_IN_FLAGS.DRS_EXT_BASE
                );

            BaseTestSite.Assert.AreEqual <uint>(
                0,
                ret,
                "IDL_DRSBind: should return 0 with a success bind to DC");

            // Create a DSNAME with only SAMAccountName.
            string userDn         = ldapAdapter.GetUserDn(server, user);
            string sAMAccountName = (string)ldapAdapter.GetAttributeValue(server, userDn, "sAMAccountName");
            DSNAME dsUser         = DrsuapiClient.CreateDsName(sAMAccountName, Guid.Empty, null);

            // Prefix table
            SCHEMA_PREFIX_TABLE prefixTable = OIDUtility.CreatePrefixTable();

            // Create the attribute block. Here we go to RDN attribute.
            string rdnAttrId = DRSConstants.RDN_OID;
            uint   attrTyp   = OIDUtility.MakeAttid(prefixTable, rdnAttrId);

            ATTRVAL      attrVal      = DrsuapiClient.CreateATTRVAL(null);
            ATTRVALBLOCK attrValBlock = DrsuapiClient.CreateATTRVALBLOCK(new ATTRVAL[] { attrVal });
            ATTR         attr         = DrsuapiClient.CreateATTR(attrTyp, attrValBlock);
            ATTRBLOCK    attrBlock    = DrsuapiClient.CreateATTRBLOCK(new ATTR[] { attr });

            // Actual RPC call.
            ret = drsTestClient.DrsVerifyNames(
                srv,
                dwInVersion_Values.V1,
                DRS_MSG_VERIFYREQ_V1_dwFlags_Values.DRS_VERIFY_SAM_ACCOUNT_NAMES,
                new DSNAME[] { dsUser },
                new string[] { userDn },
                attrBlock,
                prefixTable
                );

            BaseTestSite.Assert.AreEqual <uint>(
                0,
                ret,
                "IDL_DRSVerifyNames: return value should be 0"
                );

            // Unbind
            ret = drsTestClient.DrsUnbind(srv);
            BaseTestSite.Assert.AreEqual <uint>(
                0,
                ret,
                "IDL_DRSUnbind: return value should be 0");
        }
 string DomainDNSNameFromDomain(DsServer dc, DSNAME domainNc)
 {
     // Looks like this method also returns NetBIOS name
     // return DomainNetBIOSNameFromDomain(dc, domainNc);
     return(DrsrHelper.GetFQDNFromDN(LdapUtility.ConvertUshortArrayToString(domainNc.StringName)));
 }
        public DS_NAME_RESULT_ITEMW LookupNames(
            DsServer dc,
            uint flags,
            uint formatOffered,
            uint formatDesired,
            string name)
        {
            DS_NAME_RESULT_ITEMW result = new DS_NAME_RESULT_ITEMW();
            string referredDomain       = "";

            // Unknown name
            if (formatOffered == (uint)DS_NAME_FORMAT.DS_UNKNOWN_NAME)
            {
                return(LookupUnknownName(dc, flags, formatDesired, name));
            }

            DSNAME[] rt         = null;
            string   domainName = null;

            switch (formatOffered)
            {
            case (uint)DS_NAME_FORMAT.DS_UNKNOWN_NAME:
                return(LookupUnknownName(dc, flags, formatDesired, name));

            case (uint)DS_NAME_FORMAT.DS_FQDN_1779_NAME:
            {
                rt = LookupAttr(dc, flags, "distinguishedName", name);
                if (EnvironmentConfig.TestDS)
                {
                    DSNAME?dcDsname = GetDsName(dc, RetrieveDCSuffixFromDn(name));
                    if (dcDsname != null)
                    {
                        domainName = DomainDNSNameFromDomain(dc, dcDsname.Value);
                    }
                }
            }
            break;

            case (uint)DS_NAME_FORMAT.DS_NT4_ACCOUNT_NAME:
            {
                rt = LookupAttr(dc, flags, "sAMAccountName", LdapUtility.UserNameFromNT4AccountName(name));
                if (EnvironmentConfig.TestDS)
                {
                    domainName = LdapUtility.DomainNameFromNT4AccountName(name);
                }
            }
            break;

            case (uint)DS_NAME_FORMAT.DS_USER_PRINCIPAL_NAME:
            {
                rt = LookupUPNAndAltSecID(dc, flags, false, name);
                if (EnvironmentConfig.TestDS)
                {
                    domainName = DomainNameFromUPN(name);
                }
            }
            break;

            case (uint)DS_NAME_FORMAT.DS_CANONICAL_NAME:
            {
                DSNAME?v = LookupCanonicalName(dc, name);
                if (v != null)
                {
                    rt = new DSNAME[] { v.Value }
                }
                ;
                else
                {
                    rt = null;
                }
                if (EnvironmentConfig.TestDS)
                {
                    domainName = DomainNameFromCanonicalName(name);
                }
            }
            break;

            case (uint)DS_NAME_FORMAT.DS_UNIQUE_ID_NAME:
            {
                RootDSE rootDse = LdapUtility.GetRootDSE(dc);

                // The GUID is in the curly braced form, so we need
                // to remove the braces first.
                if (!name.Contains("{") && name.Contains("}"))
                {
                    rt = null;
                    break;
                }
                string guidStr = name.Substring(1, name.Length - 2);
                Guid   guid    = new Guid(guidStr);
                string dn      = null;

                dn = LdapUtility.GetObjectDnByGuid(dc, rootDse.rootDomainNamingContext, guid);
                if (dn == null)
                {
                    dn = LdapUtility.GetObjectDnByGuid(dc, rootDse.configurationNamingContext, guid);
                }
                if (dn == null)
                {
                    dn = LdapUtility.GetObjectDnByGuid(dc, rootDse.schemaNamingContext, guid);
                }

                if (dn == null)
                {
                    break;
                }

                rt = new DSNAME[] { LdapUtility.CreateDSNameForObject(dc, dn) };
            }
            break;

            case (uint)DS_NAME_FORMAT.DS_DISPLAY_NAME:
            {
                rt = LookupAttr(dc, flags, "displayName", name);
            }
            break;

            case (uint)DS_NAME_FORMAT.DS_SERVICE_PRINCIPAL_NAME:
            {
                rt = LookupSPN(dc, flags, name);
                if (EnvironmentConfig.TestDS)
                {
                    domainName = GetServiceNameFromSPN(name);
                }
            }
            break;

            case (uint)DS_NAME_FORMAT.DS_SID_OR_SID_HISTORY_NAME:
            case (uint)formatOffered_Values.DS_STRING_SID_NAME:
            {
                rt = LookupSID(dc, flags, SidFromStringSid(name));
                if (EnvironmentConfig.TestDS)
                {
                    domainName = DomainNameFromSid(dc, DomainSidFromSid(SidFromStringSid(name)));
                }
            }
            break;

            case (uint)DS_NAME_FORMAT.DS_CANONICAL_NAME_EX:
            {
                DSNAME?v = LookupCanonicalName(dc, CanonicalNameFromCanonicalNameEx(name));
                if (v == null)
                {
                    rt = null;
                }
                else
                {
                    rt = new DSNAME[] { v.Value }
                };

                if (EnvironmentConfig.TestDS)
                {
                    domainName = DomainNameFromCanonicalName(name);
                }
            }
            break;

            case (uint)formatOffered_Values.DS_NT4_ACCOUNT_NAME_SANS_DOMAIN:
            case (uint)formatOffered_Values.DS_NT4_ACCOUNT_NAME_SANS_DOMAIN_EX:
            {
                rt = LookupAttr(dc, flags, "sAMAccountName", name);
            }
            break;

            case (uint)formatOffered_Values.DS_ALT_SECURITY_IDENTITIES_NAME:
            {
                rt = LookupAttr(dc, flags, "altSecurityIdentities", name);
            }
            break;

            case (uint)formatOffered_Values.DS_USER_PRINCIPAL_NAME_AND_ALTSECID:
            {
                rt = LookupUPNAndAltSecID(dc, flags, true, name);
                if (EnvironmentConfig.TestDS)
                {
                    domainName = DomainNameFromUPN(name);
                }
            }
            break;

            default:
                rt = null;
                break;
            }

            if (rt == null && domainName != null)
            {
                result.status = DS_NAME_ERROR.DS_NAME_ERROR_DOMAIN_ONLY;
                if (formatOffered == (uint)DS_NAME_FORMAT.DS_NT4_ACCOUNT_NAME ||
                    formatOffered == (uint)DS_NAME_FORMAT.DS_USER_PRINCIPAL_NAME ||
                    formatOffered == (uint)DS_NAME_FORMAT.DS_SERVICE_PRINCIPAL_NAME ||
                    formatOffered == (uint)DS_NAME_FORMAT.DS_SID_OR_SID_HISTORY_NAME ||
                    formatOffered == (uint)formatOffered_Values.DS_STRING_SID_NAME ||
                    formatOffered == (uint)formatOffered_Values.DS_USER_PRINCIPAL_NAME_AND_ALTSECID)
                {
                    if (TrustInfo.IsDomainNameInTrustedForest(dc, domainName, ref referredDomain))
                    {
                        result.pDomain = referredDomain;
                        if ((flags & (uint)DRS_MSG_CRACKREQ_FLAGS.DS_NAME_FLAG_TRUST_REFERRAL) > 0)
                        {
                            result.status = DS_NAME_ERROR.DS_NAME_ERROR_TRUST_REFERRAL;
                        }
                        else
                        {
                            result.status = DS_NAME_ERROR.DS_NAME_ERROR_DOMAIN_ONLY;
                        }
                    }
                }

                return(result);
            }

            if (rt == null)
            {
                result.status = DS_NAME_ERROR.DS_NAME_ERROR_NOT_FOUND;
                return(result);
            }

            if (rt.Length > 1)
            {
                result.status = DS_NAME_ERROR.DS_NAME_ERROR_NOT_UNIQUE;
                return(result);
            }

            DSNAME obj = rt[0];

            if (formatOffered == (uint)formatOffered_Values.DS_NT4_ACCOUNT_NAME_SANS_DOMAIN_EX)
            {
                string uacStr = (string)GetAttributeValue(
                    dc,
                    LdapUtility.ConvertUshortArrayToString(obj.StringName),
                    "userAccountControl");
                uint uac = Convert.ToUInt32(uacStr);

                const uint ADS_UF_ACCOUNTDISABLE         = 0x0002;
                const uint ADS_UF_TEMP_DUPLICATE_ACCOUNT = 0x0100;
                if ((uac & (ADS_UF_ACCOUNTDISABLE | ADS_UF_TEMP_DUPLICATE_ACCOUNT)) > 0)
                {
                    result.status = DS_NAME_ERROR.DS_NAME_ERROR_NOT_FOUND;
                    return(result);
                }
            }

            string[] names = ConstructOutput(dc, obj, formatDesired);

            if ((names == null) &&
                (obj.SidLen != 0) &&
                ((flags & (uint)DRS_MSG_CRACKREQ_FLAGS.DS_NAME_FLAG_PRIVATE_RESOLVE_FPOS) > 0))
            {
                if (formatDesired == (uint)DS_NAME_FORMAT.DS_NT4_ACCOUNT_NAME ||
                    formatDesired == (uint)DS_NAME_FORMAT.DS_DISPLAY_NAME ||
                    formatDesired == (uint)DS_NAME_FORMAT.DS_CANONICAL_NAME ||
                    formatDesired == (uint)DS_NAME_FORMAT.DS_CANONICAL_NAME_EX ||
                    formatDesired == (uint)DS_NAME_FORMAT.DS_USER_PRINCIPAL_NAME ||
                    formatDesired == (uint)formatDesired_Values.DS_USER_PRINCIPAL_NAME_FOR_LOGON ||
                    formatDesired == (uint)DS_NAME_FORMAT.DS_SERVICE_PRINCIPAL_NAME)
                {
                    bool fCanonicalEx = false;
                    if (formatDesired == (uint)DS_NAME_FORMAT.DS_CANONICAL_NAME_EX)
                    {
                        fCanonicalEx = true;
                    }

                    result = LookupFPO(fCanonicalEx, obj, result);
                    return(result);
                }
            }

            if (names == null)
            {
                if (formatDesired == (uint)DS_NAME_FORMAT.DS_SID_OR_SID_HISTORY_NAME ||
                    formatDesired == (uint)DS_NAME_FORMAT.DS_UNKNOWN_NAME)
                {
                    result.status = DS_NAME_ERROR.DS_NAME_ERROR_RESOLVING;
                }
                else
                {
                    result.status = DS_NAME_ERROR.DS_NAME_ERROR_NO_MAPPING;
                }
                return(result);
            }

            if (names.Length > 1)
            {
                result.status = DS_NAME_ERROR.DS_NAME_ERROR_NOT_UNIQUE;
                return(result);
            }

            result.pName = names[0];
            if (EnvironmentConfig.TestDS)
            {
                string objDn    = LdapUtility.ConvertUshortArrayToString(obj.StringName);
                DSNAME?dcDsname = GetDsName(dc, RetrieveDCSuffixFromDn(objDn));
                string domainDn = "";
                if (dcDsname != null)
                {
                    domainDn = DomainDNSNameFromDomain(dc, dcDsname.Value);
                }

                result.pDomain = domainDn;
            }
            else
            {
                result.pDomain = "";
            }
            result.status = DS_NAME_ERROR.DS_NAME_NO_ERROR;

            return(result);
        }