コード例 #1
0
        public static string getDN(string user, string idAttribute, string telephoneAttribute, string server, string authtype, string ldapUser, string password, string targetou, string filter)
        {
            string dn = "";

            Init(server, authtype, ldapUser, password, targetou, filter);
            log.Debug("Search " + user + " from " + targetOU + " on " + ldapServer);

            SearchResponse response;

            ldapFilter = "(&(" + idAttribute + "=" + user + ")" + ldapFilter + ")";
            SearchRequest request = new SearchRequest(targetOU, ldapFilter, SearchScope.Subtree, new string[1] {
                telephoneAttribute
            });

            response = (SearchResponse)ldapConnection.SendRequest(request);
            if (response.Entries.Count == 1)
            {
                DirectoryAttribute da = response.Entries[0].Attributes[telephoneAttribute];
                if (da != null && da.GetValues(typeof(string)).Length > 0)
                {
                    dn = (string)da.GetValues(typeof(string))[0];
                }
                else
                {
                    log.Debug("The attribute " + telephoneAttribute + " is not defined for " + user);
                }
            }
            else
            {
                log.Debug("0 or more than 1 result retreived...");
            }
            return(dn);
        }
コード例 #2
0
        public void GetValues_ContainsUri_ThrowsNotSupportedException()
        {
            var attribute = new DirectoryAttribute {
                "abc", new byte[] { 100, 101, 102 }, new Uri("http://microsoft.com")
            };

            Assert.Throws <NotSupportedException>(() => attribute.GetValues(typeof(byte[])));
            Assert.Throws <NotSupportedException>(() => attribute.GetValues(typeof(string)));
        }
コード例 #3
0
ファイル: ConexionLDAP.cs プロジェクト: hrbie/ModulosTI
        /// <summary>
        /// Método que se encarga de obtener el nombre de una persona a partir de su nombre de usuario (login)
        /// </summary>
        /// <param name="nombreUsuario">Nombre de usuario (login)</param>
        /// <returns>Nombre de la persona</returns>

        public String obtenerNombrePersona(string nombreUsuario)
        {
            LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER);
            LdapConnection          openLdap   = new LdapConnection(Constantes.LDAP_SERVER);

            try
            {
                String nombrePersona;
                // Crear conexion con LDAP
                openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS);
                openLdap.AuthType   = AuthType.Basic;
                openLdap.SessionOptions.ProtocolVersion = 3;                  // Hay que usar LDAPv3
                openLdap.Bind();                                              //Conectar
                string[] attributesToReturn = new string[] { "displayName" }; // Atributos a retornar
                // Buscar al usuario por su login
                SearchRequest searchRequest = new SearchRequest("ou=people,dc=ic-itcr,dc=ac,dc=cr", "(uid=" + nombreUsuario + "*)",
                                                                System.DirectoryServices.Protocols.SearchScope.Subtree, attributesToReturn);
                SearchResponse     searchResponse = (SearchResponse)openLdap.SendRequest(searchRequest);             // Respuesta del servidor
                DirectoryAttribute atributo       = searchResponse.Entries[0].Attributes["displayName"];
                object[]           objeto         = atributo.GetValues(Type.GetType("System.Byte[]"));
                nombrePersona = Encoding.ASCII.GetString((byte[])objeto[0]);
                openLdap.Dispose();                 // Liberar recursos
                return(nombrePersona);
            }
            catch (Exception e)
            {
                openLdap.Dispose();
                _conexionBD = new ManejoBD();
                _conexionBD.insertarBitacoraError(e.ToString(), "");
                return(null);
            }
        }
コード例 #4
0
        public List <string> DecodeSchemaInfo(DirectoryAttribute attrib, out Int32 uVer)
        {
            List <string> ret = new List <string> {
            };

            uVer = 0;

            foreach (byte[] value in attrib.GetValues(typeof(byte[])))
            {
                byte[] tempar = new byte[4];

                Array.Copy(value, 1, tempar, 0, 4);

                Array.Reverse(tempar);

                uVer = BitConverter.ToInt32(tempar, 0);

                tempar = new byte[16];

                Array.Copy(value, 5, tempar, 0, 16);

                Guid invocationid = new Guid(tempar);

                ret.AddFormatted("\t\t<Update version = {0}; InvocationID= {1}>",
                                 uVer, invocationid.ToString());
            }

            return(ret);
        }
コード例 #5
0
ファイル: ConexionLDAP.cs プロジェクト: hrbie/ModulosTI
        /// <summary>
        /// Método que busca el login de un usuario basado en su numero de carné
        /// </summary>
        /// <param name="carne">Numero de carné</param>
        /// <returns>Login del usuario correspondiente al carné</returns>

        public String buscarUsuarioPorCarnet(string carne)
        {
            string uid = "";
            LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER);
            LdapConnection          openLdap   = new LdapConnection(Constantes.LDAP_SERVER);

            openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS);
            openLdap.AuthType   = AuthType.Basic;
            openLdap.SessionOptions.ProtocolVersion = 3;                                                                                      // Hay que usar LDAPv3
            openLdap.Bind();                                                                                                                  // Conectar

            string[]      attributesToReturn = new string[] { "uid" };                                                                        // Retornar solamente el login
            SearchRequest searchRequest      = new SearchRequest("ou=people,dc=ic-itcr,dc=ac,dc=cr", "(gecos=" + carne + "*)",
                                                                 System.DirectoryServices.Protocols.SearchScope.Subtree, attributesToReturn); // Buscar por carnet
            SearchResponse searchResponse = (SearchResponse)openLdap.SendRequest(searchRequest);                                              // Respuesta del servidor

            if (searchResponse.Entries.Count != 0)
            {
                DirectoryAttribute atributo = searchResponse.Entries[0].Attributes["uid"];
                object[]           objeto   = atributo.GetValues(Type.GetType("System.Byte[]"));
                uid = Encoding.ASCII.GetString((byte[])objeto[0]);
            }
            openLdap.Dispose();             // Liberar recursos
            return(uid);
        }
コード例 #6
0
        public List <string> DecodeSDData(DirectoryAttribute attrib, ActiveDirectorySyntax syntax)
        {
            List <String> ret = new List <string> {
            };

            foreach (byte[] value in attrib.GetValues(typeof(byte[])))
            {
                try
                {
                    CommonSecurityDescriptor oCSD = new CommonSecurityDescriptor(true, true, value, 0);

                    if (!MainBase.UserSettings.DecodeSD)
                    {
                        ret.AddFormatted("\t\t(must not decode) SDDL: <{0}>", oCSD.GetSddlForm(AccessControlSections.All));
                    }

                    else
                    {
                        ret.AddRange(DecodeSD(oCSD));
                    }
                }

                catch
                { ret.AddFormatted("\t\t<not decoded>: {0}", attrib[0].GetType().ToString()); }
            }

            return(ret);
        }
コード例 #7
0
        public virtual string GetTargetPath(ExSearchResultEntry entry)
        {
            string text;

            if (this.type == SyncTreeType.Recipients)
            {
                DirectoryAttribute directoryAttribute = entry.Attributes["objectGUID"];
                Guid guid = new Guid((byte[])directoryAttribute.GetValues(typeof(byte[]))[0]);
                text = "cn=" + guid.ToString() + ",CN=Recipients,OU=MSExchangeGateway";
            }
            else
            {
                if (LdapTargetConnection.rootOrgContainerDN == null)
                {
                    LdapTargetConnection.rootOrgContainerDN = ADSystemConfigurationSession.GetRootOrgContainerIdForLocalForest().DistinguishedName;
                }
                string text2      = entry.DistinguishedName;
                int    startIndex = -1;
                int    count      = 0;
                if (entry.IsCollisionObject(out startIndex, out count))
                {
                    text2 = text2.Remove(startIndex, count);
                }
                text = text2.Replace(LdapTargetConnection.rootOrgContainerDN, this.adamRootOrgContainerDN);
            }
            ExTraceGlobals.SynchronizationJobTracer.TraceDebug <string, string>((long)this.GetHashCode(), "Translate source DN {0} to target DN {1}", entry.DistinguishedName, text);
            return(text);
        }
コード例 #8
0
 /// <summary>
 /// 結果を出力します。
 /// </summary>
 /// <param name="searchResultEntry">ログインに成功したユーザー。</param>
 private static void OutputResult(SearchResultEntry searchResultEntry)
 {
     if (searchResultEntry != null)
     {
         Console.WriteLine("[[[ authn succeeded. ]]]");
         Console.WriteLine();
         foreach (DictionaryEntry dictionaryEntry in searchResultEntry.Attributes)
         {
             DirectoryAttribute directoryAttribute = dictionaryEntry.Value as DirectoryAttribute;
             // 属性名の出力
             Console.Write(directoryAttribute.Name + ": ");
             foreach (string valueString in directoryAttribute.GetValues(typeof(string)))
             {
                 // 雑にすべての値を文字列として出力するので、内容によっては文字化ける。
                 Console.Write(valueString + ", ");;
             }
             Console.WriteLine();
         }
         Console.WriteLine();
     }
     else
     {
         Console.WriteLine("[[[ authn failed. ]]]");
     }
 }
コード例 #9
0
        public static string[] GetAttributeValuesString(
            DsServer dc, string dn, string attributeName,
            string ldapFilter = "(objectClass=*)",
            System.DirectoryServices.Protocols.SearchScope searchScope
            = System.DirectoryServices.Protocols.SearchScope.Base)
        {
            SearchResultEntryCollection results = null;
            ResultCode ret = Search(
                dc,
                dn,
                ldapFilter,
                searchScope,
                new string[] { attributeName },
                out results);

            if (ret != ResultCode.Success)
            {
                return(null);
            }

            foreach (SearchResultEntry e in results)
            {
                DirectoryAttribute attr = e.Attributes[attributeName];
                if (attr == null)
                {
                    return(null);
                }
                else
                {
                    return((string[])attr.GetValues(typeof(string)));
                }
            }

            return(null);
        }
コード例 #10
0
 public override void UpdateModifyRequestForTarget(TenantRelocationSyncTranslator translator, DirectoryAttribute sourceValue, ref DirectoryAttributeModification mod)
 {
     object[] values = sourceValue.GetValues(typeof(T));
     foreach (object obj in values)
     {
         Guid guid = this.GetGuid(obj);
         if (guid.Equals(EmailAddressPolicy.PolicyGuid) || Guid.Empty.Equals(guid))
         {
             if (this.IsString)
             {
                 mod.Add((string)obj);
             }
             else
             {
                 mod.Add((byte[])obj);
             }
         }
         else
         {
             DistinguishedNameMapItem distinguishedNameMapItem = translator.Mappings.LookupByCorrelationGuid(guid);
             if (distinguishedNameMapItem == null)
             {
                 this.AddValue(mod, guid);
             }
             else
             {
                 this.AddValue(mod, distinguishedNameMapItem.TargetDN.ObjectGuid);
             }
         }
     }
     mod.Name      = sourceValue.Name;
     mod.Operation = DirectoryAttributeOperation.Replace;
 }
コード例 #11
0
ファイル: ConexionLDAP.cs プロジェクト: hrbie/ModulosTI
        /// <summary>
        /// Método que retorna el proximo identificador unico libre
        /// </summary>
        /// <returns>Identificador único libre</returns>

        private String obtenerNumeroUid()
        {
            string uid = "";
            LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER);
            LdapConnection          openLdap   = new LdapConnection(Constantes.LDAP_SERVER);

            openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS);
            openLdap.AuthType   = AuthType.Basic;
            openLdap.SessionOptions.ProtocolVersion = 3;                                                                                      // Hay que usar LDAPv3
            openLdap.Bind();                                                                                                                  // Conectar
            string[]      attributesToReturn = new string[] { "uidNumber" };                                                                  // Retornar solamente el uid number
            SearchRequest searchRequest      = new SearchRequest("dc=ic-itcr,dc=ac,dc=cr", "(cn=NextFreeUnixId)",
                                                                 System.DirectoryServices.Protocols.SearchScope.Subtree, attributesToReturn); // Buscar al objeto NextFreeUnixId
            SearchResponse searchResponse = (SearchResponse)openLdap.SendRequest(searchRequest);                                              // Respuesta del servidor
            // Manejar la respuesta
            DirectoryAttribute atributo = searchResponse.Entries[0].Attributes["uidNumber"];

            object[] objeto = atributo.GetValues(Type.GetType("System.Byte[]"));
            uid = Encoding.ASCII.GetString((byte[])objeto[0]);
            int           siguienteuid = Int32.Parse(uid) + 1;                                                                           // Actualizar el Unix Id libre
            ModifyRequest incremento   = new ModifyRequest("cn=NextFreeUnixId,dc=ic-itcr,dc=ac,dc=cr"
                                                           , DirectoryAttributeOperation.Replace, "uidNumber", siguienteuid.ToString()); // Modificar el NextFreeUnixId en el servidor

            openLdap.SendRequest(incremento);
            openLdap.Dispose();
            return(uid);            // Retornar el uid
        }
コード例 #12
0
ファイル: ConexionLDAP.cs プロジェクト: hrbie/ModulosTI
        public Usuario buscarUsuario(string clave)
        {
            Usuario                 user       = new Usuario();
            List <String>           datos      = new List <String>();
            LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER);
            LdapConnection          openLdap   = new LdapConnection(Constantes.LDAP_SERVER);

            openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS);
            openLdap.AuthType   = AuthType.Basic;
            openLdap.SessionOptions.ProtocolVersion = 3; // Hay que usar LDAPv3
            openLdap.Bind();                             // Conectar


            string[]      attributesToReturn = new string[] { "gecos", "cn", "sn", "homePhone", "mobile", "mail", "description" };            // Retornar solamente el login
            SearchRequest searchRequest      = new SearchRequest("ou=people,dc=ic-itcr,dc=ac,dc=cr", "(uid=" + clave + "*)",
                                                                 System.DirectoryServices.Protocols.SearchScope.Subtree, attributesToReturn); // Buscar por carnet
            SearchResponse searchResponse = (SearchResponse)openLdap.SendRequest(searchRequest);                                              // Respuesta del servidor

            if (searchResponse.Entries.Count == 0)
            {
                return(null);
            }
            //Cambiar a String cada atributo del usuario
            for (int i = 0; i < attributesToReturn.Length; i++)
            {
                DirectoryAttribute atributo = searchResponse.Entries[0].Attributes[attributesToReturn[i]];
                if (atributo != null)
                {
                    object[] objeto = atributo.GetValues(Type.GetType("System.Byte[]"));
                    datos.Add(Encoding.ASCII.GetString((byte[])objeto[0]));
                }
                else
                {
                    datos.Add("Atributo Nulo!");
                }
            }
            user.Carnet          = datos.ElementAt(0).Split(' ')[0];            // Carnet
            user.Nombre          = datos.ElementAt(1);                          // Nombre
            user.Apellidos       = datos.ElementAt(2);                          // Apellidos
            user.TelefonoCasa    = datos.ElementAt(3);                          // Teléfono Fijo
            user.TelefonoCelular = datos.ElementAt(4);                          // Teléfono Celular
            user.Correo          = datos.ElementAt(5);                          // Correo
            user.Grupo           = datos.ElementAt(6);                          // Descripcion
            user.UID             = clave;                                       // Login

            if (datos.ElementAt(0).Split(' ').Length > 4)
            {
                user.Carrera = datos.ElementAt(0).Split(' ')[4];                        // Carrera
            }
            else
            {
                user.Carrera = "IC";
            }

            openLdap.Dispose();                        //Liberar recursos

            return(user);
        }
コード例 #13
0
ファイル: Login.aspx.cs プロジェクト: blockspacer/turtle
    public void ValidateUser(object sender, EventArgs e)
    {
        UserProfile user    = new UserProfile(form_login.UserName);
        String      uid     = string.Format("uid={0}", user.UserName);
        String      basedn  = "ou=Employees,o=lexmark";
        String      ldapusr = string.Format("{0},{1}", uid, basedn);
        String      passwd  = form_login.Password;

        try
        {
            string ldap_host = string.Format("{0}:{1}", Config.LdapServer, Config.LdapPort);
            LdapDirectoryIdentifier ldapDirectoryIdentifier = new LdapDirectoryIdentifier(ldap_host, true, false);
            NetworkCredential       credentials             = new NetworkCredential(ldapusr, passwd);
            using (LdapConnection ldapConnection = new LdapConnection(ldapDirectoryIdentifier, credentials, AuthType.Basic))
            {
                ldapConnection.SessionOptions.SecureSocketLayer = false;
                ldapConnection.SessionOptions.ProtocolVersion   = 3; // LDAP_OPT_PROTOCOL_VERSION
                ldapConnection.Bind();

                // distinguished name of the object
                // at which to start the search.

                SearchRequest  searchRequest = new SearchRequest(basedn, string.Format("({0})", uid), System.DirectoryServices.Protocols.SearchScope.Subtree, null);
                SearchResponse response      = (SearchResponse)ldapConnection.SendRequest(searchRequest);

                if (response.Entries.Count == 1)
                {
                    string [] keys = new string[]
                    {
                        "displayname",
                        "lexorgpersonmail"
                    };
                    SearchResultEntry entry = response.Entries[0];
                    foreach (string key in keys)
                    {
                        DirectoryAttribute attr = entry.Attributes[key];
                        user[key] = attr.GetValues(typeof(string)).GetValue(0).ToString();

                        string log = string.Format("{0} = {1}", key, user[key]);
                        Console.WriteLine(log);
                    }

                    Master.VisibleWhenLoggedIn = true;
                    Master.CurrentUserName     = form_login.UserName;
                    Session["current_user"]    = user;
                    FormsAuthentication.RedirectFromLoginPage(form_login.UserName, form_login.RememberMeSet);
                }
                else
                {
                    throw new Exception("Multiple match for {0}" + user.UserName);
                }
            }
        }
        catch (Exception err)
        {
            form_login.FailureText = err.Message;
        }
    }
コード例 #14
0
        public void GetValues_Mixed_Success()
        {
            var attribute = new DirectoryAttribute {
                "abc", new byte[] { 100, 101, 102 }
            };

            Assert.Equal(new byte[][] { new byte[] { 97, 98, 99 }, new byte[] { 100, 101, 102 } }, attribute.GetValues(typeof(byte[])));
            Assert.Equal(new string[] { "abc", "def" }, attribute.GetValues(typeof(string)));
        }
コード例 #15
0
        public static KeyValuePair <string, string> GetAttributeNameAndValue(DirectoryAttribute attribute)
        {
            if (attribute == null)
            {
                throw new ArgumentNullException(nameof(attribute));
            }

            return(new KeyValuePair <string, string>(attribute.Name, attribute.GetValues(typeof(String))[0].ToString()));
        }
コード例 #16
0
        public static EhfCompanyAdmins CreateEhfCompanyAdmins(EhfAdminSyncChangeBuilder ehfAdminSyncChangeBuilder, EhfTargetConnection ehfTargetConnection, EhfADAdapter configADAdapter)
        {
            ExSearchResultEntry exSearchResultEntry = configADAdapter.ReadObjectEntry(ehfAdminSyncChangeBuilder.ConfigUnitDN, false, EhfCompanyAdmins.OtherWellKnownObjectsAttribute);

            if (exSearchResultEntry == null)
            {
                ehfTargetConnection.DiagSession.LogAndTraceError("Could not find Configuration Unit for company {0}. The config naming context is either not replicated or the organization is deleted", new object[]
                {
                    ehfAdminSyncChangeBuilder.TenantOU
                });
                return(null);
            }
            string             text      = null;
            string             text2     = null;
            DirectoryAttribute attribute = exSearchResultEntry.GetAttribute("otherWellKnownObjects");

            if (attribute == null)
            {
                ehfTargetConnection.DiagSession.LogAndTraceError("Could not find OtherWellKnownObjects attribute in Configuration Unit object for company {0}.", new object[]
                {
                    ehfAdminSyncChangeBuilder.TenantOU
                });
                return(null);
            }
            foreach (object obj in attribute.GetValues(typeof(string)))
            {
                DNWithBinary dnwithBinary;
                if (DNWithBinary.TryParse(obj as string, out dnwithBinary))
                {
                    try
                    {
                        Guid b = new Guid(dnwithBinary.Binary);
                        if (WellKnownGuid.EoaWkGuid == b)
                        {
                            text = dnwithBinary.DistinguishedName;
                        }
                        if (WellKnownGuid.EraWkGuid == b)
                        {
                            text2 = dnwithBinary.DistinguishedName;
                        }
                        if (text != null && text2 != null)
                        {
                            break;
                        }
                    }
                    catch (ArgumentException exception)
                    {
                        ehfTargetConnection.DiagSession.LogAndTraceException(exception, "OtherWellKnownObjects attribute for company {0} contains an entry with invalid Binary part.", new object[]
                        {
                            ehfAdminSyncChangeBuilder.TenantOU
                        });
                    }
                }
            }
            return(new EhfCompanyAdmins(ehfAdminSyncChangeBuilder, ehfTargetConnection, text, text2, configADAdapter));
        }
コード例 #17
0
        public override object FormatValueFromDirectory(DirectoryAttribute value, string dn)
        {
            if (value != null)
            {
                try
                {
                    var strings = Array.ConvertAll(value.GetValues(typeof(string)), obj => obj.ToString());

                    if (_isNullable)
                    {
                        var dates = new DateTime?[strings.Length];

                        for (int i = 0; i < strings.Length; i++)
                        {
                            var str      = strings[i];
                            var dateTime = _isFileTimeFormat
                                                    ? DateTime.FromFileTime(long.Parse(str))
                                                    : str.FormatLdapDateTime(_dateFormat);

                            dates[i] = dateTime;
                        }

                        return(dates);
                    }
                    else
                    {
                        var dates = new DateTime[strings.Length];

                        for (int i = 0; i < strings.Length; i++)
                        {
                            var str      = strings[i];
                            var dateTime = _isFileTimeFormat
                                                    ? DateTime.FromFileTime(long.Parse(str))
                                                    : str.FormatLdapDateTime(_dateFormat);

                            dates[i] = dateTime;
                        }

                        return(dates);
                    }
                }
                catch (Exception ex)
                {
                    ThrowMappingException(value, dn, ex);
                }
            }

            if (DirectoryValueMappings != null && DirectoryValueMappings.ContainsKey(string.Empty))
            {
                return(DirectoryValueMappings[string.Empty]);
            }

            AssertNullable(dn);

            return(null);
        }
コード例 #18
0
        public void LDAP_Search_ConstructedAttributes_isUserCachableAtRodc()
        {
            if (string.IsNullOrWhiteSpace(AD_LDAPModelAdapter.Instance(Site).RODCNetbiosName))
            {
                BaseTestSite.Assert.Fail("Test case requires a RODC but \"RODCName\" ptfconfig property value is invalid");
            }

            #region variables

            string RODCName = AD_LDAPModelAdapter.Instance(Site).RODCNetbiosName;
            string RODCDN   = "CN=" + RODCName + ",OU=Domain Controllers," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC;
            //Let D be the DN of the user principal specified using LDAP Control LDAP_SERVER_DN_INPUT_OID.
            //If the DN of a security principal is not explicitly specified, D is the DN of the current requester.
            string userName   = AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName;
            string userDN     = "CN=" + userName + ",CN=Users," + AD_LDAPModelAdapter.Instance(Site).rootDomainNC;
            bool   isCachable = false;

            #endregion

            #region connect

            BaseTestSite.Assume.IsTrue(EnvironmentConfig.ServerVer >= ServerVersion.Win2012, "Server OS version should be not less than Windows Server 2012");
            LdapConnection con = new LdapConnection(new LdapDirectoryIdentifier(AD_LDAPModelAdapter.Instance(Site).PDCIPAddress),
                                                    new NetworkCredential(AD_LDAPModelAdapter.Instance(Site).DomainAdministratorName,
                                                                          AD_LDAPModelAdapter.Instance(Site).DomainUserPassword,
                                                                          AD_LDAPModelAdapter.Instance(Site).PrimaryDomainDnsName));
            con.SessionOptions.Sealing = false;
            con.SessionOptions.Signing = false;

            #endregion

            #region search with LDAP_SERVER_DN_INPUT_OID

            System.DirectoryServices.Protocols.SearchRequest searchReq = new System.DirectoryServices.Protocols.SearchRequest(
                RODCDN,
                "(objectClass=computer)",
                System.DirectoryServices.Protocols.SearchScope.Subtree,
                "msDS-isUserCachableAtRodc");
            //Let D be the DN of the user principal specified using LDAP Control LDAP_SERVER_DN_INPUT_OID.
            //If the DN of a security principal is not explicitly specified, D is the DN of the current requester.
            System.DirectoryServices.Protocols.SearchResponse searchRep = (System.DirectoryServices.Protocols.SearchResponse)con.SendRequest(searchReq);
            DirectoryAttribute attr   = searchRep.Entries[0].Attributes["msDS-isUserCachableAtRodc"];
            object[]           values = attr.GetValues(Type.GetType("System.String"));
            isCachable = Convert.ToBoolean(Convert.ToInt16(values[0].ToString(), CultureInfo.InvariantCulture));

            //Get expected result by GetRevealSecretsPolicyForUser(TO!distinguishedName, D) defined in MS-DRSR section 4.1.10.5.14
            bool expectedCachable = GetRevealSecretsPolicyForUser(RODCDN, userDN);

            BaseTestSite.Assert.AreEqual(
                expectedCachable,
                isCachable,
                @"TO!msDS-IsUserCachableAtRodc = GetRevealSecretsPolicyForUser(TO!distinguishedName, D) (procedure GetRevealSecretsPolicyForUser is defined in [MS-DRSR] section 4.1.10.5.14).");

            #endregion
        }
コード例 #19
0
        private static RangeResult GetRangeBlock(LdapConnection conn, string entryDn, string attrName, int start, int?end, bool extendedDns)
        {
            SearchRequest req = new SearchRequest();

            req.DistinguishedName = entryDn;
            req.Scope             = SearchScope.Base;
            req.Filter            = "(&(objectClass=*))";
            req.Attributes.Add(attrName + ";range=" + start + "-" + (end == null ? "*" : end.ToString()));

            if (extendedDns)
            {
                req.Controls.Add(new ExtendedDNControl(ExtendedDNFlag.StandardString));
            }

            SearchResponse resp = (SearchResponse)conn.SendRequest(req);

            if (resp.Entries.Count == 0)
            {
                return(null);
            }

            SearchResultEntry e = resp.Entries[0];

            foreach (string s in e.Attributes.AttributeNames)
            {
                if (s.StartsWith(attrName, StringComparison.InvariantCultureIgnoreCase))
                {
                    RangeResult        res  = new RangeResult();
                    DirectoryAttribute attr = e.Attributes[s];

                    res.Values = (string[])attr.GetValues(typeof(string));

                    if (s.EndsWith("*"))
                    {
                        res.IsFinal = true;
                    }

                    int pos = s.IndexOf('=');
                    int hyp = s.IndexOf('-', pos + 1);

                    res.Start = int.Parse(s.Substring(pos + 1, hyp - pos - 1));

                    if (!res.IsFinal)
                    {
                        res.End = int.Parse(s.Substring(hyp + 1));
                    }

                    return(res);
                }
            }

            return(null);
        }
コード例 #20
0
        public List <string> DecodeDsaSignature(DirectoryAttribute attrib)
        {
            List <string> ret = new List <string> {
            };

            foreach (byte[] value in attrib.GetValues(typeof(byte[])))
            {
                ret.AddRange(DsaSignature.Decode(value));
            }

            return(ret);
        }
コード例 #21
0
        public void Ctor_DistinguishedName_ObjectClass(string distinguishedName, string objectClass)
        {
            var request = new AddRequest(distinguishedName, objectClass);
            DirectoryAttribute attribute = (DirectoryAttribute)Assert.Single(request.Attributes);

            Assert.Equal("objectClass", attribute.Name);
            Assert.Equal(new string[] { objectClass }, attribute.GetValues(typeof(string)));

            Assert.Empty(request.Controls);
            Assert.Equal(distinguishedName, request.DistinguishedName);
            Assert.Null(request.RequestId);
        }
コード例 #22
0
ファイル: ConexionLDAP.cs プロジェクト: hrbie/ModulosTI
        public Boolean verificarProfesor(string clave)
        {
            String descripcion = String.Empty;
            LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER);
            LdapConnection          openLdap   = new LdapConnection(Constantes.LDAP_SERVER);

            openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS);
            openLdap.AuthType   = AuthType.Basic;
            openLdap.SessionOptions.ProtocolVersion = 3; // Hay que usar LDAPv3
            openLdap.Bind();                             // Conectar

            // El criterio seleccionado es "Login" true
            //  if (!tipoBusqueda)
            //   clave = buscarUsuarioPorCarnet(clave);


            Boolean res = false;

            string[]      attributesToReturn = new string[] { "description" };                                                                // Retornar solamente el login
            SearchRequest searchRequest      = new SearchRequest("ou=people,dc=ic-itcr,dc=ac,dc=cr", "(uid=" + clave + "*)",
                                                                 System.DirectoryServices.Protocols.SearchScope.Subtree, attributesToReturn); // Buscar por carnet
            SearchResponse searchResponse = (SearchResponse)openLdap.SendRequest(searchRequest);                                              // Respuesta del servidor

            if (searchResponse.Entries.Count == 0)
            {
                return(res);
            }
            //Cambiar a String cada atributo del usuario
            if (attributesToReturn.Length > 0)
            {
                DirectoryAttribute atributo = searchResponse.Entries[0].Attributes["description"];
                if (atributo != null)
                {
                    object[] objeto = atributo.GetValues(Type.GetType("System.Byte[]"));
                    descripcion = Encoding.ASCII.GetString((byte[])objeto[0]);
                }
                else
                {
                    return(res);
                }
            }

            if (descripcion == "Profesor")
            {
                res = true;
            }


            openLdap.Dispose();                        //Liberar recursos

            return(res);
        }
コード例 #23
0
        public override object FormatValueFromDirectory(DirectoryAttribute value, string dn)
        {
            if (value != null)
            {
                SecurityIdentifier[] identifiers = Array.ConvertAll(value.GetValues(typeof(byte[])), obj => new SecurityIdentifier((byte[])obj, 0));

                return(identifiers);
            }

            AssertNullable(dn);

            return(null);
        }
コード例 #24
0
        public override object FormatValueFromDirectory(DirectoryAttribute value, string dn)
        {
            if (value != null)
            {
                if (_isX5092)
                {
                    var certs = value.GetValues(typeof(byte[]))
                                .Select(c => new X509Certificate2((byte[])c));
                    return(new System.Collections.ObjectModel.Collection <X509Certificate2>(certs.ToList()));
                }
                else
                {
                    var certs = value.GetValues(typeof(byte[]))
                                .Select(c => new X509Certificate((byte[])c));
                    return(new System.Collections.ObjectModel.Collection <X509Certificate>(certs.ToList()));
                }
            }

            AssertNullable(dn);

            return(null);
        }
コード例 #25
0
        public override object FormatValueFromDirectory(DirectoryAttribute value, string dn)
        {
            if (value != null)
            {
                byte[][] bytes = Array.ConvertAll(value.GetValues(typeof(byte[])), obj => (byte[])obj);

                return(bytes);
            }

            AssertNullable(dn);

            return(null);
        }
コード例 #26
0
        public override object FormatValueFromDirectory(DirectoryAttribute value, string dn)
        {
            if (value != null)
            {
                var bytes = value.GetValues(typeof(byte[]))
                            .Select(c => (byte[])c);

                return(new System.Collections.ObjectModel.Collection <byte[]>(bytes.ToList()));
            }

            AssertNullable(dn);

            return(null);
        }
コード例 #27
0
        public List <string> DecodeLogonHours(DirectoryAttribute attrib)
        {
            List <string> ret = new List <string>()
            {
                "\t\tSun:\t", "\t\tMon:\t", "\t\tTue:\t", "\t\tWen:\t", "\t\tThu:\t", "\t\tFri:\t", "\t\tSat:\t"
            };

            List <char[]> bhours = new List <char[]>();

            char[] th;

            foreach (byte[] value in attrib.GetValues(typeof(byte[])))
            {
                for (int cnt = 1; cnt < value.Count(); cnt++)
                {
                    th = NormalizeCharHours(value[cnt]);

                    bhours.Add(th);
                }

                th = NormalizeCharHours(value[0]);

                bhours.Add(th);
            }

            string temp = String.Empty;

            int daycnt = 0;

            for (int cnt = 0; cnt < (bhours.Count - 2); cnt += 3)
            {
                temp = String.Empty;

                int inv = 0;

                for (int icnt = cnt; icnt < cnt + 3; icnt++)
                {
                    temp += HoursFromCharArray(bhours[icnt], inv);

                    inv++;
                }

                ret[daycnt] += temp;

                daycnt++;
            }

            return(ret);
        }
コード例 #28
0
        public override object FormatValueFromDirectory(DirectoryAttribute value, string dn)
        {
            if (value != null)
            {
                if (_isX5092)
                {
                    X509Certificate2[] certs = Array.ConvertAll(value.GetValues(typeof(byte[])),
                                                                obj =>
                                                                new X509Certificate2((byte[])obj));
                    return(certs);
                }
                else
                {
                    X509Certificate[] certs = Array.ConvertAll(value.GetValues(typeof(byte[])),
                                                               obj =>
                                                               new X509Certificate((byte[])obj));
                    return(certs);
                }
            }

            AssertNullable(dn);

            return(null);
        }
コード例 #29
0
        public static bool AuthenticateAndAuthorize(string user, string password, string telephoneNumber, string idAttribute, string telephoneAttribute, string server, string targetou, string filter, string authtype)
        {
            bool authenticated = false;

            Init(server, "Basic", user, password, targetou, filter);
            log.Debug("Search " + user + " from " + targetOU + " on " + ldapServer);

            SearchResponse response;

            ldapFilter = "(&(" + idAttribute + "=" + user + ")" + ldapFilter + ")";
            SearchRequest request = new SearchRequest(targetOU, ldapFilter, SearchScope.Subtree, new string[1] {
                telephoneAttribute
            });

            response = (SearchResponse)ldapConnection.SendRequest(request);
            if (response.Entries.Count == 1)
            {
                DirectoryAttribute da = response.Entries[0].Attributes[telephoneAttribute];
                if (da != null && da.GetValues(typeof(string)).Length > 0)
                {
                    if (telephoneNumber == (string)da.GetValues(typeof(string))[0])
                    {
                        authenticated = true;
                    }
                }
                else
                {
                    log.Debug("The attribute " + telephoneAttribute + " is not defined for " + user);
                }
            }
            else
            {
                log.Debug("0 or more than 1 result retreived...");
            }
            return(authenticated);
        }
コード例 #30
0
        protected virtual ExSearchResultEntry GetTargetEntry(ExSearchResultEntry entry)
        {
            DirectoryAttribute directoryAttribute = entry.Attributes["objectGUID"];

            byte[]         value          = (byte[])directoryAttribute.GetValues(typeof(byte[]))[0];
            string         str            = ADValueConvertor.EscapeBinaryValue(value);
            SearchRequest  request        = new SearchRequest(this.GetTargetBaseSearchPath(), "(msExchEdgeSyncSourceGuid=" + str + ")", System.DirectoryServices.Protocols.SearchScope.Subtree, new string[0]);
            SearchResponse searchResponse = (SearchResponse)this.SendRequest(request);

            if (searchResponse.Entries.Count > 0)
            {
                return(new ExSearchResultEntry(searchResponse.Entries[0]));
            }
            return(null);
        }