The name and values of one attribute of a directory entry. LdapAttribute objects are used when searching for, adding, modifying, and deleting attributes from the directory. LdapAttributes are often used in conjunction with an {@link LdapAttributeSet} when retrieving or adding multiple attributes to an entry.
Inheritance: System.ICloneable, System.IComparable
Exemplo n.º 1
0
        public LdapUser(DirectoryEntry adentry, String userName, LdapSettings ldapSettings)
        {
            userid = new LdapAttribute("userid", userName);
            DirectorySearcher ds = new DirectorySearcher(adentry);
            ds.Filter = "(&(sAMAccountName=" + userName + "))";
            SearchResult result = ds.FindOne();
            DirectoryEntry ent = null;

            if (result != null)
            {
                ent = result.GetDirectoryEntry();
            }

            if (ent != null)
            {
                if (ent.Properties["cn"].Value != null)
                {
                    commonname = new LdapAttribute("commonname", ent.Properties["cn"].Value.ToString());
                }
                else
                {
                    commonname = new LdapAttribute("commonname", userName);
                }
                if (ent.Properties["mail"].Value != null)
                {
                    email = new LdapAttribute("email", ent.Properties["mail"].Value.ToString());
                }
                else
                {
                    email = new LdapAttribute("email", userName + "@" + ldapSettings.Domain);
                }
            }
        }
Exemplo n.º 2
0
    public static void doCleanup(LdapConnection conn, System.String userdn, System.String groupdn)
    {
        // since we have modified the user's attributes and failed to
        // modify the group's attribute, we need to delete the modified
        // user's attribute values.

        // modifications for user
        LdapModification[] modUser = new LdapModification[2];

        // Delete the groupdn from the user's attributes
        LdapAttribute membership = new LdapAttribute("groupMembership", groupdn);
        modUser[0] = new LdapModification(LdapModification.DELETE, membership);
        LdapAttribute security = new LdapAttribute("securityEquals", groupdn);
        modUser[1] = new LdapModification(LdapModification.DELETE, security);

        try
        {
            // Modify the user's attributes
            conn.Modify(userdn, modUser);

            System.Console.Out.WriteLine("Deleted the modified user's attribute values.");
        }
        catch (LdapException e)
        {
            System.Console.Out.WriteLine("Could not delete modified user's attributes: " + e.LdapErrorMessage);
        }
        catch(Exception e)
        {
            Console.WriteLine("Error:" + e.Message);
            return;
        }

        return ;
    }
Exemplo n.º 3
0
			public URLData(LdapAttribute enclosingInstance, sbyte[] data, int length)
			{
				InitBlock(enclosingInstance);
				this.length = length;
				this.data = data;
				return ;
			}
Exemplo n.º 4
0
    public static void Main(System.String[] args)
    {
        if (args.Length != 5)
        {
            System.Console.Out.WriteLine("Usage:   mono VerifyPassword <host name>" + " <login dn> <password> <object dn>\n" + "         <test password>");
            System.Console.Out.WriteLine("Example: mono VerifyPassword Acme.com " + "\"cn=Admin,o=Acme\" secret\n" + "         \"cn=JSmith,ou=Sales,o=Acme\" testPassword");
            System.Environment.Exit(0);
        }

        int ldapPort = LdapConnection.DEFAULT_PORT;
        int ldapVersion = LdapConnection.Ldap_V3;
        System.String ldapHost = args[0];
        System.String loginDN = args[1];
        System.String password = args[2];
        System.String objectDN = args[3];
        System.String testPassword = args[4];
        LdapConnection conn = new LdapConnection();

        try
        {
            // connect to the server
            conn.Connect(ldapHost, ldapPort);

            // authenticate to the server
            conn.Bind(ldapVersion, loginDN, password);

            LdapAttribute attr = new LdapAttribute("userPassword", testPassword);
            bool correct = conn.Compare(objectDN, attr);

            System.Console.Out.WriteLine(correct?"The password is correct.":"The password is incorrect.\n");

            // disconnect with the server
            conn.Disconnect();
        }
        catch (LdapException e)
        {
            if (e.ResultCode == LdapException.NO_SUCH_OBJECT)
            {
                System.Console.Error.WriteLine("Error: No such entry");
            }
            else if (e.ResultCode == LdapException.NO_SUCH_ATTRIBUTE)
            {
                System.Console.Error.WriteLine("Error: No such attribute");
            }
            else
            {
                System.Console.Error.WriteLine("Error: " + e.ToString());
            }
        }
        catch (System.IO.IOException e)
        {
            System.Console.Out.WriteLine("Error: " + e.ToString());
        }
        System.Environment.Exit(0);
    }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            if ( args.Length != 5)
            {
            Console.WriteLine("Usage:   mono ModifyEntry <host name> <ldap port>  <login dn>" + " <password> <Modify dn>");
            Console.WriteLine("Example: mono ModifyEntry Acme.com 389"  + " \"cn=admin,o=Acme\"" + " secret \"cn=ksmith,o=Acme\"");
            return;
            }

            string ldapHost = args[0];
            int ldapPort = System.Convert.ToInt32(args[1]);
            String loginDN  = args[2];
            String password = args[3];
            String dn = args[4];

            try
            {
            Console.WriteLine("Connecting to:" + ldapHost);
            LdapConnection conn= new LdapConnection();
            ArrayList modList = new ArrayList();
            String desc = "This object belongs to test user";
            // Add a new value to the description attribute
            LdapAttribute attribute = new LdapAttribute( "description", desc);
            modList.Add( new LdapModification(LdapModification.ADD, attribute));

            String email = "*****@*****.**";
            attribute = new LdapAttribute( "mail", email);
            modList.Add( new LdapModification(LdapModification.REPLACE, attribute));
            LdapModification[] mods = new LdapModification[modList.Count];
            mods = (LdapModification[])modList.ToArray(typeof(LdapModification));

            conn.Connect(ldapHost,ldapPort);
            conn.Bind(loginDN,password);
            conn.Modify(dn,mods);
            Console.WriteLine(" Entry: " + dn + "Modified Successfully");
            conn.Disconnect();

            }
            catch(LdapException e)
            {
            Console.WriteLine("Error:" + e.LdapErrorMessage);
            return;
            }
            catch(Exception e)
            {
            Console.WriteLine("Error:" + e.Message);
            return;
            }
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            if ( args.Length != 5)
            {
            Console.WriteLine("Usage:   mono ModifyPass <host name> <ldap port>  <login dn>" + " <old password> <new password>");
            Console.WriteLine("Example: mono ModifyPass Acme.com 389"  + " \"cn=tjhon,o=Acme\"" + " secret \"newpass\"");
            return;
            }

            string ldapHost = args[0];
            int ldapPort = System.Convert.ToInt32(args[1]);
            String loginDN  = args[2];
            String opassword = args[3];
            String npassword = args[4];

            try
            {
            LdapConnection conn= new LdapConnection();
            Console.WriteLine("Connecting to:" + ldapHost);
            conn.Connect(ldapHost,ldapPort);
            conn.Bind(loginDN,opassword);
            LdapModification[] modifications = new LdapModification[2];
            LdapAttribute deletePassword = new LdapAttribute("userPassword", opassword);
            modifications[0] = new LdapModification(LdapModification.DELETE, deletePassword);
            LdapAttribute addPassword = new LdapAttribute("userPassword", npassword);
            modifications[1] = new LdapModification(LdapModification.ADD, addPassword);

            conn.Modify(loginDN, modifications);

            System.Console.Out.WriteLine("Your password has been modified.");

            conn.Disconnect();
            }
            catch(LdapException e)
            {
            Console.WriteLine("Error:" + e.LdapErrorMessage);
            return;
            }
            catch(Exception e)
            {
            Console.WriteLine("Error:" + e.Message);
            return;
            }
        }
Exemplo n.º 7
0
        private System.Object[] values = null; // Array of byte[] attribute values

        #endregion Fields

        #region Constructors

        /// <summary> Constructs an attribute with copies of all values of the input
        /// attribute.
        /// 
        /// </summary>
        /// <param name="attr"> An LdapAttribute to use as a template.
        /// 
        /// @throws IllegalArgumentException if attr is null
        /// </param>
        public LdapAttribute(LdapAttribute attr)
        {
            if (attr == null)
            {
                throw new System.ArgumentException("LdapAttribute class cannot be null");
            }
            // Do a deep copy of the LdapAttribute template
            this.name = attr.name;
            this.baseName = attr.baseName;
            if (null != attr.subTypes)
            {
                this.subTypes = new System.String[attr.subTypes.Length];
                Array.Copy((System.Array) attr.subTypes, 0, (System.Array) this.subTypes, 0, this.subTypes.Length);
            }
            // OK to just copy attributes, as the app only sees a deep copy of them
            if (null != attr.values)
            {
                this.values = new System.Object[attr.values.Length];
                Array.Copy((System.Array) attr.values, 0, (System.Array) this.values, 0, this.values.Length);
            }
            return ;
        }
Exemplo n.º 8
0
		/// <summary> Asynchronously compares an attribute value with one in the directory,
		/// using the specified queue and contraints.
		/// 
		/// Please note that a successful completion of this command results in
		/// one of two status codes: LdapException.COMPARE_TRUE if the entry
		/// has the value, and LdapException.COMPARE_FALSE if the entry
		/// does not have the value or the attribute.
		/// 
		/// </summary>
		/// <param name="dn">     The distinguished name of the entry containing an
		/// attribute to compare.
		/// 
		/// </param>
		/// <param name="attr">   An attribute to compare.
		/// 
		/// </param>
		/// <param name="queue">    Handler for messages returned from a server in
		/// response to this request. If it is null, a
		/// queue object is created internally.
		/// 
		/// </param>
		/// <param name="cons">     Constraints specific to the operation.
		/// 
		/// </param>
		/// <exception> LdapException A general exception which includes an error
		/// message and an Ldap error code.
		/// 
		/// </exception>
		/// <seealso cref="LdapException.COMPARE_TRUE">
		/// </seealso>
		/// <seealso cref="LdapException.COMPARE_FALSE">
		/// </seealso>
		public virtual LdapResponseQueue Compare(System.String dn, LdapAttribute attr, LdapResponseQueue queue, LdapConstraints cons)
		{
			if (attr.size() != 1)
			{
				throw new System.ArgumentException("compare: Exactly one value " + "must be present in the LdapAttribute");
			}
			
			if ((System.Object) dn == null)
			{
				// Invalid parameter
				throw new System.ArgumentException("compare: DN cannot be null");
			}
			
			if (cons == null)
				cons = defSearchCons;
			
			LdapMessage msg = new LdapCompareRequest(dn, attr.Name, attr.ByteValue, cons.getControls());
			
			return SendRequestToServer(msg, cons.TimeLimit, queue, null);
		}
Exemplo n.º 9
0
		/// <summary> 
		/// Synchronously checks to see if an entry contains an attribute with a
		/// specified value, using the specified constraints.
		/// 
		/// </summary>
		/// <param name="dn">     The distinguished name of the entry to use in the
		/// comparison.
		/// 
		/// </param>
		/// <param name="attr">   The attribute to compare against the entry. The
		/// method checks to see if the entry has an
		/// attribute with the same name and value as this
		/// attribute.
		/// 
		/// </param>
		/// <param name="cons">   Constraints specific to the operation.
		/// 
		/// </param>
		/// <returns> True if the entry has the value,
		/// and false if the entry does not
		/// have the value or the attribute.
		/// 
		/// </returns>
		/// <exception> LdapException A general exception which includes an error
		/// message and an Ldap error code.
		/// </exception>
		public virtual bool Compare(System.String dn, LdapAttribute attr, LdapConstraints cons)
		{
			bool ret = false;
			
			LdapResponseQueue queue = Compare(dn, attr, null, cons);
			
			LdapResponse res = (LdapResponse) queue.getResponse();
			
			// Set local copy of responseControls synchronously - if there were any
			lock (responseCtlSemaphore)
			{
				responseCtls = res.Controls;
			}
			
			if (res.ResultCode == LdapException.COMPARE_TRUE)
			{
				ret = true;
			}
			else if (res.ResultCode == LdapException.COMPARE_FALSE)
			{
				ret = false;
			}
			else
			{
				chkResultCode(queue, cons, res);
			}
			return ret;
		}
		private void CommitEntry()
		{
			PropertyCollection properties = GetProperties(false);
			if(!Nflag)
			{
				System.Collections.ArrayList modList = new System.Collections.ArrayList();
				foreach (string attribute in properties.PropertyNames)
				{
					LdapAttribute attr=null;
					if (properties [attribute].Mbit)
					{
						switch (properties [attribute].Count) {
							case 0:
								attr = new LdapAttribute (attribute, new string [0]);
								modList.Add (new LdapModification (LdapModification.DELETE, attr));
								break;
							case 1:
								string val = (string) properties [attribute].Value;
								attr = new LdapAttribute (attribute, val);
								modList.Add (new LdapModification (LdapModification.REPLACE, attr));
								break;
							default:
								object [] vals = (object [])properties [attribute].Value;
								string [] aStrVals = new string [properties [attribute].Count];
								Array.Copy (vals, 0, aStrVals, 0, properties [attribute].Count);
								attr = new LdapAttribute (attribute, aStrVals);
								modList.Add (new LdapModification (LdapModification.REPLACE, attr));
								break;
						}
						properties [attribute].Mbit=false;
					}
				}
				if (modList.Count > 0) {
					LdapModification[] mods = new LdapModification[modList.Count]; 	
					Type mtype = typeof (LdapModification);
					mods = (LdapModification[])modList.ToArray(mtype);
					ModEntry(mods);
				}
			}
			else
			{
				LdapAttributeSet attributeSet = new LdapAttributeSet();
				foreach (string attribute in properties.PropertyNames)
				{
					if (properties [attribute].Count == 1)
					{
						string val = (string) properties [attribute].Value;
						attributeSet.Add(new LdapAttribute(attribute, val));                
					}
					else
					{
						object[] vals = (object []) properties [attribute].Value;
						string[] aStrVals = new string [properties [attribute].Count];
						Array.Copy (vals,0,aStrVals,0,properties [attribute].Count);
						attributeSet.Add( new LdapAttribute( attribute , aStrVals));
					}
				}
				LdapEntry newEntry = new LdapEntry( Fdn, attributeSet );
				conn.Add( newEntry );
				Nflag = false;
			}
		}
Exemplo n.º 11
0
 private static bool AttrEquals(LdapAttribute attr, ATTRNAME name)
 {
     if (attr.Name.ToUpper().Equals(name.ToString()))
         return true;
     return false;
 }
Exemplo n.º 12
0
        public void OnOkClicked(object o, EventArgs args)
        {
            Connection conn = GetCurrentConnection ();

            LdapEntry[] sr = conn.Data.Search (conn.DirectoryRoot, searchEntry.Text);

            foreach (object[] row in modListStore) {

                string _action = (string) row[0];
                string _name = (string) row[1];
                string _value = (string) row[2];

                LdapAttribute a = new LdapAttribute (_name, _value);
                LdapModification m = null;

                switch (_action.ToLower()) {

                case "add":
                    m = new LdapModification (LdapModification.ADD, a);
                    break;

                case "delete":
                    m = new LdapModification (LdapModification.DELETE, a);
                    break;

                case "replace":
                    m = new LdapModification (LdapModification.REPLACE, a);
                    break;

                default:
                    break;
                }

                if (m != null)
                    _modList.Add (m);
            }

            foreach (LdapEntry e in sr) {
                Util.ModifyEntry (conn, e.DN, _modList.ToArray());
            }

            massEditDialog.HideAll ();
        }
Exemplo n.º 13
0
    public static void Main( String[] args )
    {
        if (args.Length != 6)
        {
            Console.Error.WriteLine(
                 "Usage:   mono ModifyACL <host name> <port number> <login dn>"
                 + " <password> \n         <entry dn> <trustee dn>");
            Console.Error.WriteLine(
                 "Example: mono ModifyACL Acme.com 389 \"cn=Admin,o=Acme\""
                 + "  secret \n         \"cn=test,ou=Sales,o=Acme\" "
                 + "\"cn=trustee,o=Acme\"");
            Environment.Exit(1);
        }
        int privileges   = 0;
        int ldapVersion  = LdapConnection.Ldap_V3;
        int ldapPort     = System.Convert.ToInt32(args[1]);
        String ldapHost  = args[0];
        String loginDN   = args[2];
        String password  = args[3];
        String entryDN   = args[4];
        String trusteeDN = args[5];

        LdapConnection lc = new LdapConnection();

        // encode ACL value
        privileges |= System.Convert.ToInt32(LdapDSConstants.LDAP_DS_ENTRY_BROWSE);
        privileges |= System.Convert.ToInt32(LdapDSConstants.LDAP_DS_ENTRY_ADD);
        privileges |= System.Convert.ToInt32(LdapDSConstants.LDAP_DS_ENTRY_DELETE);

        String aclValue = System.Convert.ToString(privileges)+ "#" + "entry" + "#"
                            + trusteeDN + "#" + "[Entry Rights]";

        try
        {
            // connect to the server
            lc.Connect( ldapHost, ldapPort );
            // bind to the server
            lc.Bind(ldapVersion, loginDN, password);

            // modify entryDN's ACL attribute
            Console.WriteLine( "    Entry DN: " + entryDN );
            Console.WriteLine( "    Trustee DN: " + trusteeDN );
            Console.WriteLine( "    Modifying entryDN's ACL value...");

            LdapAttribute acl = new LdapAttribute( "acl", aclValue);
            lc.Modify( entryDN, new LdapModification(LdapModification.ADD, acl));
            Console.WriteLine("    Modified ACL values to grant trusteeDN  the"
                        + "\n      'read', 'write', and 'delete' entry rights.\n");

            // display entryDN's ACL values
            findACLValues(lc, entryDN);

            // remove the Modified entryDN's ACL value
            Console.WriteLine( "\n    Removing the modified ACL value..." );
            lc.Modify( entryDN, new LdapModification(LdapModification.DELETE,acl));
            Console.WriteLine( "    Removed modified ACL value." );

            lc.Disconnect();
        }
        catch( LdapException e )
        {
            if ( e.ResultCode == LdapException.NO_SUCH_OBJECT )
                Console.Error.WriteLine( "Error: ModifyACL.java, No such entry" );
            else if ( e.ResultCode == LdapException.INSUFFICIENT_ACCESS_RIGHTS )
                Console.Error.WriteLine("Error: ModifyACL.java, Insufficient rights");
            else if ( e.ResultCode == LdapException.ATTRIBUTE_OR_VALUE_EXISTS )
                Console.Error.WriteLine("Error: ModifyACL.java, Attribute or value "
                                + "exists");
            else
            {
                Console.WriteLine( "Error: ModifyACL.java, " + e.ToString() );
            }
            Environment.Exit(1);
        }
        catch( Exception e )
        {
            Console.WriteLine( "Error: " + e.ToString() );
        }
        Environment.Exit(0);
    }
Exemplo n.º 14
0
        /// <summary> Returns <code>true</code> if this set contains an attribute of the same name
        /// as the specified attribute.
        ///
        /// </summary>
        /// <param name="attr">  Object of type <code>LdapAttribute</code>
        ///
        /// </param>
        /// <returns> true if this set contains the specified attribute
        ///
        /// @throws ClassCastException occurs the specified Object
        /// is not of type LdapAttribute.
        /// </returns>
        public override bool Contains(object attr)
        {
            LdapAttribute attribute = (LdapAttribute)attr;

            return(map.ContainsKey(attribute.Name.ToUpper()));
        }
Exemplo n.º 15
0
 public UrlData(LdapAttribute enclosingInstance, byte[] data, int length)
 {
     EnclosingInstance = enclosingInstance;
     _length           = length;
     _data             = data;
 }
Exemplo n.º 16
0
 /// <summary> Specifies a modification to be made to an attribute.
 ///
 /// </summary>
 /// <param name="op">      The type of modification to make, which can be
 /// one of the following:
 /// <ul>
 /// <li>LdapModification.ADD - The value should be added to
 /// the attribute</li>
 ///
 /// <li>LdapModification.DELETE - The value should be removed
 /// from the attribute </li>
 ///
 /// <li>LdapModification.REPLACE - The value should replace all
 /// existing values of the
 /// attribute </li>
 /// </ul>
 /// </param>
 /// <param name="attr">    The attribute to modify.
 ///
 /// </param>
 public LdapModification(int op, LdapAttribute attr)
 {
     this.op   = op;
     this.attr = attr;
     return;
 }
Exemplo n.º 17
0
 public URLData(LdapAttribute enclosingInstance, sbyte[] data, int length)
 {
     InitBlock(enclosingInstance);
     this.length = length;
     this.data   = data;
 }
Exemplo n.º 18
0
 private void InitBlock(LdapAttribute enclosingInstance)
 {
     this.enclosingInstance = enclosingInstance;
 }
Exemplo n.º 19
0
		private void CommitEntry()
		{
			if(!Nflag)
			{
				System.Collections.ArrayList modList = new System.Collections.ArrayList();
				System.Collections.IDictionaryEnumerator id = Properties.GetEnumerator();
				while(id.MoveNext())
				{
					string attribute=(string)id.Key;
					LdapAttribute attr=null;
					if(Properties[attribute].Mbit)
					{
						if(Properties[attribute].Count==1)
						{
							String val = (String)Properties[attribute].Value;
							attr = new LdapAttribute( attribute , val);
						}
						else
						{
							Object[] vals=(Object [])Properties[attribute].Value;
							String[] aStrVals= new String[Properties[attribute].Count];
							Array.Copy(vals,0,aStrVals,0,Properties[attribute].Count);
							attr = new LdapAttribute( attribute , aStrVals);
						}
						modList.Add( new LdapModification(LdapModification.REPLACE, attr));
						Properties[attribute].Mbit=false;
					}
				}
				if (modList.Count > 0) {
					LdapModification[] mods = new LdapModification[modList.Count]; 	
					Type mtype=Type.GetType("System.DirectoryServices.LdapModification");
					mods = (LdapModification[])modList.ToArray(typeof(LdapModification));
					ModEntry(mods);
				}
			}
			else
			{
				LdapAttributeSet attributeSet = new LdapAttributeSet();
				System.Collections.IDictionaryEnumerator id = Properties.GetEnumerator();
				while(id.MoveNext())
				{
					string attribute=(string)id.Key;
					if(Properties[attribute].Count==1)
					{
						String val = (String)Properties[attribute].Value;
						attributeSet.Add(new LdapAttribute(attribute, val));                
					}
					else
					{
						Object[] vals=(Object [])Properties[attribute].Value;
						String[] aStrVals= new String[Properties[attribute].Count];
						Array.Copy(vals,0,aStrVals,0,Properties[attribute].Count);
						attributeSet.Add( new LdapAttribute( attribute , aStrVals));
					}
				}
				LdapEntry newEntry = new LdapEntry( Fdn, attributeSet );
				conn.Add( newEntry );
				Nflag = false;
			}
		}
Exemplo n.º 20
0
        /// <summary>Copy a directory entry
        /// </summary>
        /// <param name="oldDN">Distinguished name of the entry to copy</param>
        /// <param name="newRDN">New name for entry</param>
        /// <param name="parentDN">Parent name</param>
        public void Copy(string oldDN, string newRDN, string parentDN)
        {
            string newDN = string.Format ("{0},{1}", newRDN, parentDN);

            LdapEntry[] entry = Search (oldDN, LdapConnection.SCOPE_BASE, "objectclass=*", null);
            if (!(entry.Length > 0))
                return;

            LdapEntry oldEntry = entry[0];
            LdapAttributeSet attributeSet = new LdapAttributeSet();

            foreach (LdapAttribute attr in oldEntry.getAttributeSet()) {
                LdapAttribute newAttr = new LdapAttribute (attr);
                attributeSet.Add (newAttr);
            }

            LdapEntry le = new LdapEntry (newDN, attributeSet);
            conn.Add (le);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Compares current values in eDirectory with the values of the object that is to be written to eDirectory
        /// The results are returned as an LdapModifications array
        /// </summary>
        /// <param name="newApp">
        /// A <see cref="LDAPZFDApp"/>
        /// </param>
        /// <param name="oldApp">
        /// A <see cref="LDAPZFDApp"/>
        /// </param>
        /// <returns>
        /// A <see cref="LdapModification[]"/>
        /// </returns>
        internal static ArrayList BuildZFDAppModifications(LDAPZFDApp newApp, LDAPZFDApp oldApp)
        {
            LdapAttribute attribute;
            ArrayList modList = new ArrayList();

            /* If associations list do not match, replace */
            if (newApp.getZENAppAssociations().SequenceEqual(oldApp.getZENAppAssociations()) == false) {

                Logger.Debug("Current Associations and modified Associations do not match {0}", newApp.getDN());

                attribute = new LdapAttribute( "appAssociations", newApp.getZENAppAssociations().ToArray());
                modList.Add( new LdapModification(LdapModification.REPLACE, attribute)); //Add to the list of mods
            }

            return modList;
        }
Exemplo n.º 22
0
    public static bool _AddUserToGroup(LdapConnection conn, System.String userdn, System.String groupdn)
    {
        // modifications for group and user
        LdapModification[] modGroup = new LdapModification[2];
        LdapModification[] modUser = new LdapModification[2];

        // Add modifications to modUser
        LdapAttribute membership = new LdapAttribute("groupMembership", groupdn);
        modUser[0] = new LdapModification(LdapModification.ADD, membership);
        LdapAttribute security = new LdapAttribute("securityEquals", groupdn);
        modUser[1] = new LdapModification(LdapModification.ADD, security);

        // Add modifications to modGroup
        LdapAttribute member = new LdapAttribute("uniqueMember", userdn);
        modGroup[0] = new LdapModification(LdapModification.ADD, member);
        LdapAttribute equivalent = new LdapAttribute("equivalentToMe", userdn);
        modGroup[1] = new LdapModification(LdapModification.ADD, equivalent);

        try
        {
            // Modify the user's attributes
            conn.Modify(userdn, modUser);
            System.Console.Out.WriteLine("Modified the user's attribute.");
        }
        catch (LdapException e)
        {
            System.Console.Out.WriteLine("Failed to modify user's attributes: " + e.LdapErrorMessage);
            return false;
        }

        try
        {
            // Modify the group's attributes
            conn.Modify(groupdn, modGroup);
            System.Console.Out.WriteLine("Modified the group's attribute.");
        }
        catch (LdapException e)
        {
            System.Console.Out.WriteLine("Failed to modify group's attributes: " + e.LdapErrorMessage);
            doCleanup(conn, userdn, groupdn);
            return false;
        }
        catch(Exception e)
        {
            Console.WriteLine("Error:" + e.Message);
            return false;
        }
        return true;
    }
Exemplo n.º 23
0
        void ChangePassword(LdapEntry entry, PasswordDialog pd)
        {
            List<LdapModification> mods = new List<LdapModification> ();

            LdapAttribute la;
            LdapModification lm;

            la = new LdapAttribute ("userPassword", pd.UnixPassword);
            lm = new LdapModification (LdapModification.REPLACE, la);
            mods.Add (lm);

            if (Util.CheckSamba (entry)) {
                la = new LdapAttribute ("sambaLMPassword", pd.LMPassword);
                lm = new LdapModification (LdapModification.REPLACE, la);
                mods.Add (lm);

                la = new LdapAttribute ("sambaNTPassword", pd.NTPassword);
                lm = new LdapModification (LdapModification.REPLACE, la);
                mods.Add (lm);
            }

            Util.ModifyEntry (conn, entry.DN, mods.ToArray());
        }
Exemplo n.º 24
0
        public void OnAddGroupClicked(object o, EventArgs args)
        {
            List<string> tmp = new List<string> ();

            foreach (KeyValuePair<string, LdapEntry> kvp in _allGroups) {
                if (kvp.Key == primaryGroupLabel.Text || _memberOfGroups.ContainsKey (kvp.Key))
                    continue;

                tmp.Add (kvp.Key);
            }

            SelectGroupsDialog sgd = new SelectGroupsDialog (tmp.ToArray ());

            foreach (string name in sgd.SelectedGroupNames) {

                _memberOfStore.AppendValues (name);

                if (!_memberOfGroups.ContainsKey (name))
                    _memberOfGroups.Add (name, "memberUid");

                LdapAttribute attr = new LdapAttribute ("memberUid", conn.Data.GetAttributeValueFromEntry (currentEntry, "uid"));
                LdapModification lm = new LdapModification (LdapModification.ADD, attr);

                _modsGroup.Add (name, lm);

                updateGroupMembership ();

                _modsGroup.Clear ();
            }
        }
Exemplo n.º 25
0
			private void  InitBlock(LdapAttribute enclosingInstance)
			{
				this.enclosingInstance = enclosingInstance;
			}
Exemplo n.º 26
0
        public void OnRemoveGroupClicked(object o, EventArgs args)
        {
            TreeModel model;
            TreeIter iter;

            TreePath[] tp = memberOfTreeview.Selection.GetSelectedRows (out model);

            for (int i  = tp.Length; i > 0; i--) {

                _memberOfStore.GetIter (out iter, tp[(i - 1)]);

                string name = (string) _memberOfStore.GetValue (iter, 0);

                _memberOfStore.Remove (ref iter);

                if (_memberOfGroups.ContainsKey (name))
                    _memberOfGroups.Remove (name);

                LdapAttribute attr = new LdapAttribute ("memberUid", conn.Data.GetAttributeValueFromEntry (currentEntry, "uid"));
                LdapModification lm = new LdapModification (LdapModification.DELETE, attr);

                _modsGroup.Add (name, lm);

                updateGroupMembership ();

                _modsGroup.Clear ();
            }
        }
Exemplo n.º 27
0
    public static void Main( String[] args )
    {
        if (args.Length != 4)
        {
            Console.Error.WriteLine("Usage:   mono CompareAttrs <host name> <login dn> "
                + "<password> <compare dn> ");
            Console.Error.WriteLine("Example: mono CompareAttrs Acme.com \"cn=Admin,"
                + "o=Acme\" secret\n         \"cn=JSmith,ou=Sales,o=Acme\"");
            Environment.Exit(1);
        }

        int ldapPort = LdapConnection.DEFAULT_PORT;
        int ldapVersion = LdapConnection.Ldap_V3;
        bool compareResults = false;
        String ldapHost = args[0];
        String loginDN  = args[1];
        String password = args[2];
        String dn = args[3];
        LdapConnection lc = new LdapConnection();
        LdapAttribute attr = null;

        try
        {
            // connect to the server
            lc.Connect( ldapHost, ldapPort );

            // authenticate to the server
            lc.Bind( ldapVersion, loginDN, password );

            attr =new LdapAttribute( "objectclass", "inetOrgPerson" );
            System.Collections.IEnumerator allValues = attr.StringValues;
            allValues.MoveNext();
            // Compare the value of the objectclass attribute.
            if ( compareResults == lc.Compare(dn, attr))
                Console.WriteLine("\t" + (String)allValues.Current
                           + " is contained in the " + attr.Name + " attribute." );
            else
                Console.WriteLine("\t" + (String)allValues.Current
                           + " is not contained in the " + attr.Name + " attribute." );

            attr = new LdapAttribute( "sn", "Bunny" );
            allValues = attr.StringValues;
            allValues.MoveNext();

            // Compare the value of the sn attribute.
            if ( compareResults == lc.Compare(dn, attr))
                Console.WriteLine("\t" + (String)allValues.Current
                           + " is contained in the " + attr.Name + " attribute." );
            else
                Console.WriteLine("\t" + (String)allValues.Current
                           + " is not contained in the " + attr.Name + " attribute." );

            // disconnect with the server
            lc.Disconnect();
        }
        catch( LdapException e )
        {
            Console.WriteLine( "Error: " + e.ToString() );
        }
        catch( Exception e )
        {
            Console.WriteLine( "Error: " + e.ToString() );
        }
        Environment.Exit(0);
    }
Exemplo n.º 28
0
        static bool IsAttributeEmpty(LdapAttribute attribute)
        {
            if (attribute == null)
                return true;

            if (attribute.size() == 0)
                return true;

            if (attribute.StringValue == null || attribute.StringValue == "")
                return true;

            return false;
        }
Exemplo n.º 29
0
		//*************************************************************************
		// compare methods
		//*************************************************************************
		
		/// <summary> 
		/// Synchronously checks to see if an entry contains an attribute
		/// with a specified value.
		/// 
		/// </summary>
		/// <param name="dn">     The distinguished name of the entry to use in the
		/// comparison.
		/// 
		/// </param>
		/// <param name="attr">   The attribute to compare against the entry. The
		/// method checks to see if the entry has an
		/// attribute with the same name and value as this
		/// attribute.
		/// 
		/// </param>
		/// <returns> True if the entry has the value,
		/// and false if the entry does not
		/// have the value or the attribute.
		/// 
		/// </returns>
		/// <exception> LdapException A general exception which includes an error
		/// message and an Ldap error code.
		/// </exception>
		public virtual bool Compare(System.String dn, LdapAttribute attr)
		{
			return Compare(dn, attr, defSearchCons);
		}
Exemplo n.º 30
0
        public void Run(LdapEntry lhs, LdapEntry rhs)
        {
            Log.Debug ("Starting LdapEntryAnalyzer");

            if (lhs.CompareTo (rhs) != 0) {
                Log.Debug ("Entry DNs don't match\nlhs: {0}\nrhs: {1}", lhs.DN, rhs.DN);
                return;
            }

            LdapAttributeSet las = lhs.getAttributeSet ();
            foreach (LdapAttribute la in las) {
                LdapAttribute rla = rhs.getAttribute (la.Name);
                if (rla == null){

                    Log.Debug ("Delete attribute {0} from {1}", la.Name, lhs.DN);
                    LdapAttribute a = new LdapAttribute (la.Name);
                    LdapModification m = new LdapModification (LdapModification.DELETE, a);
                    mods.Add (m);

                } else {

                    if (rla.StringValueArray.Length > 1) {

                        Log.Debug ("Replacing attribute {0} with multiple values", la.Name);
                        LdapAttribute a = new LdapAttribute (la.Name, rla.StringValueArray);
                        LdapModification m = new LdapModification (LdapModification.REPLACE, a);
                        mods.Add (m);

                    } else if (la.StringValue != rla.StringValue) {

                        LdapAttribute newattr;
                        LdapModification lm;

                        if (rla.StringValue == "" || rla.StringValue == null) {
                            Log.Debug ("Delete attribute {0} from {1}", la.Name, lhs.DN);
                            newattr = new LdapAttribute (la.Name);
                            lm = new LdapModification (LdapModification.DELETE, newattr);
                        } else {
                            Log.Debug ("Replace attribute {0} value from {1} to {2} ", la.Name, la.StringValue, rla.StringValue);
                            newattr = new LdapAttribute (la.Name, rla.StringValue);
                            lm = new LdapModification (LdapModification.REPLACE, newattr);
                        }

                        mods.Add (lm);
                    }
                }
            }

            LdapAttributeSet rlas = rhs.getAttributeSet ();
            foreach (LdapAttribute la in rlas) {
                LdapAttribute lla = lhs.getAttribute (la.Name);
                if (lla == null && la.StringValue != string.Empty) {
                    Log.Debug ("Add attribute {0} value [{1}] to {2}", la.Name, la.StringValue, lhs.DN);
                    LdapAttribute a = new LdapAttribute (la.Name, la.StringValue);
                    LdapModification m = new LdapModification (LdapModification.ADD, a);
                    mods.Add (m);
                }
            }

            Log.Debug ("End LdapEntryAnalyzer");
        }
Exemplo n.º 31
0
		/// <summary> Asynchronously compares an attribute value with one in the directory,
		/// using the specified queue.
		/// 
		/// Please note that a successful completion of this command results in
		/// one of two status codes: LdapException.COMPARE_TRUE if the entry
		/// has the value, and LdapException.COMPARE_FALSE if the entry
		/// does not have the value or the attribute.
		/// 
		/// </summary>
		/// <param name="dn">     The distinguished name of the entry containing an
		/// attribute to compare.
		/// 
		/// </param>
		/// <param name="attr">   An attribute to compare.
		/// 
		/// </param>
		/// <param name="queue">  The queue for messages returned from a server in
		/// response to this request. If it is null, a
		/// queue object is created internally.
		/// 
		/// </param>
		/// <exception> LdapException A general exception which includes an error
		/// message and an Ldap error code.
		/// 
		/// </exception>
		/// <seealso cref="LdapException.COMPARE_TRUE">
		/// </seealso>
		/// <seealso cref="LdapException.COMPARE_FALSE">
		/// </seealso>
		public virtual LdapResponseQueue Compare(System.String dn, LdapAttribute attr, LdapResponseQueue queue)
		{
			return Compare(dn, attr, queue, defSearchCons);
		}
Exemplo n.º 32
0
 /// <summary> Specifies a modification to be made to an attribute.
 /// 
 /// </summary>
 /// <param name="op">      The type of modification to make, which can be
 /// one of the following:
 /// <ul>
 /// <li>LdapModification.ADD - The value should be added to
 /// the attribute</li>
 /// 
 /// <li>LdapModification.DELETE - The value should be removed
 /// from the attribute </li>
 /// 
 /// <li>LdapModification.REPLACE - The value should replace all
 /// existing values of the
 /// attribute </li>
 /// </ul>
 /// </param>
 /// <param name="attr">    The attribute to modify.
 /// 
 /// </param>
 public LdapModification(int op, LdapAttribute attr)
 {
     this.op = op;
     this.attr = attr;
     return ;
 }
Exemplo n.º 33
0
 public String ConvNull2Blank(LdapAttribute str)
 {
     if (str == null)
         return " ";
     else
         return str.StringValue;
 }
Exemplo n.º 34
0
        public void OnOkClicked(object o, EventArgs args)
        {
            string dn = String.Format ("{0},{1}", rdnEntry.Text, browseButton.Label);
            LdapAttributeSet lset = new LdapAttributeSet ();

            foreach (object[] row in attrListStore) {

                string n = (string) row[0];
                string v = (string) row[1];

                if (n == null || v == null || v == "")
                    continue;

                if (n.ToLower() == "objectclass") {
                    if (objAttr == null)
                        objAttr = new LdapAttribute (n, v);
                    else
                        objAttr.addValue (v);

                } else {

                    LdapAttribute attr = new LdapAttribute (n, v);
                    lset.Add (attr);
                }
            }

            lset.Add (objAttr);

            LdapEntry entry = new LdapEntry (dn, lset);
            if (!Util.AddEntry (conn, entry))
                errorOccured = true;
            else
                errorOccured = false;
        }
Exemplo n.º 35
0
        //public LdapUser(LdapSettings ldapSettings, String userName)
        //{
        //    // in some cases with Active Directory
        //    // we can't actually retrieve ldap entries
        //    // we really just need to create a mojoportal user
        //    // from the ldap user so if we can't read it, just create an ldap user
        //    // with the properties we do have
        //    // Active Directory allows us to bind a connection for authentication
        //    // even if we can't query for entries
        //    email = new LdapAttribute("email", userName + "@" + ldapSettings.Domain);
        //    commonname = new LdapAttribute("commonname", userName);
        //    userid = new LdapAttribute("userid", userName);
        //}
        public LdapUser(LdapEntry entry)
        {
            dn = entry.DN;

            LdapAttributeSet las = entry.getAttributeSet();

            foreach(LdapAttribute a in las)
            {
                switch(a.Name)
                {
                    case "mail":
                        this.email = a;
                        break;
                    case "cn":
                        this.commonname = a;
                        break;
                    case "userPassword":
                        this.password = a;
                        break;
                    case "uidNumber":
                        this.uidNumber = a;
                        break;
                    case "uid":
                        this.userid = a;
                        break;
                    case "sAMAccountName":
                        this.userid = a;
                        break;
                    case "givenName":
                        this.firstName = a.StringValue;
                        break;
                    case "sn":
                        this.lastName = a.StringValue;
                        break;
                }
            }
        }
Exemplo n.º 36
0
        /// <summary> Constructs an LdapSchema object from attributes of an LdapEntry.
        /// The object is empty if the entry parameter contains no schema
        /// attributes.  The recognized schema attributes are the following:
        /// <pre><code>
        /// "attributeTypes", "objectClasses", "ldapSyntaxes",
        /// "nameForms", "dITContentRules", "dITStructureRules",
        /// "matchingRules","matchingRuleUse"
        /// </code></pre>
        /// </summary>
        /// <param name="ent">         An LdapEntry containing schema information.
        /// </param>
        public LdapSchema(LdapEntry ent) : base(ent.DN, ent.getAttributeSet())
        {
            InitBlock();
            //reset all definitions
            for (int i = 0; i < schemaTypeNames.Length; i++)
            {
                idTable[i]   = new System.Collections.Hashtable();
                nameTable[i] = new System.Collections.Hashtable();
            }
            System.Collections.IEnumerator itr = base.getAttributeSet().GetEnumerator();
            while (itr.MoveNext())
            {
                LdapAttribute attr = (LdapAttribute)itr.Current;
                System.String value_Renamed, attrName = attr.Name;
                System.Collections.IEnumerator enumString = attr.StringValues;

                if (attrName.ToUpper().Equals(schemaTypeNames[OBJECT_CLASS].ToUpper()))
                {
                    LdapObjectClassSchema classSchema;
                    while (enumString.MoveNext())
                    {
                        value_Renamed = ((System.String)enumString.Current);
                        try
                        {
                            classSchema = new LdapObjectClassSchema(value_Renamed);
                        }
                        catch (System.Exception e)
                        {
                            continue;                             //Error parsing: do not add this definition
                        }
                        addElement(OBJECT_CLASS, classSchema);
                    }
                }
                else if (attrName.ToUpper().Equals(schemaTypeNames[ATTRIBUTE].ToUpper()))
                {
                    LdapAttributeSchema attrSchema;
                    while (enumString.MoveNext())
                    {
                        value_Renamed = ((System.String)enumString.Current);
                        try
                        {
                            attrSchema = new LdapAttributeSchema(value_Renamed);
                        }
                        catch (System.Exception e)
                        {
                            continue;                             //Error parsing: do not add this definition
                        }
                        addElement(ATTRIBUTE, attrSchema);
                    }
                }
                else if (attrName.ToUpper().Equals(schemaTypeNames[SYNTAX].ToUpper()))
                {
                    LdapSyntaxSchema syntaxSchema;
                    while (enumString.MoveNext())
                    {
                        value_Renamed = ((System.String)enumString.Current);
                        syntaxSchema  = new LdapSyntaxSchema(value_Renamed);
                        addElement(SYNTAX, syntaxSchema);
                    }
                }
                else if (attrName.ToUpper().Equals(schemaTypeNames[MATCHING].ToUpper()))
                {
                    LdapMatchingRuleSchema matchingRuleSchema;
                    while (enumString.MoveNext())
                    {
                        value_Renamed      = ((System.String)enumString.Current);
                        matchingRuleSchema = new LdapMatchingRuleSchema(value_Renamed, null);
                        addElement(MATCHING, matchingRuleSchema);
                    }
                }
                else if (attrName.ToUpper().Equals(schemaTypeNames[MATCHING_USE].ToUpper()))
                {
                    LdapMatchingRuleUseSchema matchingRuleUseSchema;
                    while (enumString.MoveNext())
                    {
                        value_Renamed         = ((System.String)enumString.Current);
                        matchingRuleUseSchema = new LdapMatchingRuleUseSchema(value_Renamed);
                        addElement(MATCHING_USE, matchingRuleUseSchema);
                    }
                }
                else if (attrName.ToUpper().Equals(schemaTypeNames[DITCONTENT].ToUpper()))
                {
                    LdapDITContentRuleSchema dITContentRuleSchema;
                    while (enumString.MoveNext())
                    {
                        value_Renamed        = ((System.String)enumString.Current);
                        dITContentRuleSchema = new LdapDITContentRuleSchema(value_Renamed);
                        addElement(DITCONTENT, dITContentRuleSchema);
                    }
                }
                else if (attrName.ToUpper().Equals(schemaTypeNames[DITSTRUCTURE].ToUpper()))
                {
                    LdapDITStructureRuleSchema dITStructureRuleSchema;
                    while (enumString.MoveNext())
                    {
                        value_Renamed          = ((System.String)enumString.Current);
                        dITStructureRuleSchema = new LdapDITStructureRuleSchema(value_Renamed);
                        addElement(DITSTRUCTURE, dITStructureRuleSchema);
                    }
                }
                else if (attrName.ToUpper().Equals(schemaTypeNames[NAME_FORM].ToUpper()))
                {
                    LdapNameFormSchema nameFormSchema;
                    while (enumString.MoveNext())
                    {
                        value_Renamed  = ((System.String)enumString.Current);
                        nameFormSchema = new LdapNameFormSchema(value_Renamed);
                        addElement(NAME_FORM, nameFormSchema);
                    }
                }
                //All non schema attributes are ignored.
                continue;
            }
        }