Monday, 23 April 2018

Java code to read objectSID from LDAP (Active Directory)

//Java code to read objectSID from LDAP (Active Directory)

import java.io.IOException;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class LDAPSID {

public static String getObjectSID(String objectName) {
Hashtable env = new Hashtable(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
    //Domain
String dirRoot = "DC=ABCD,DC=CORP";
    //LDAP User Name
String adminName = "CN=Rakesh,OU=XXX,OU=XXX,OU=XXX,DC=XXX";
    //LDAP Password
String adminPassword ="password";
    //Ldap URL
String ldapURL ="ldap://localhost:389";
    env.put(Context.SECURITY_AUTHENTICATION,"simple");
    env.put(Context.SECURITY_PRINCIPAL,adminName);
    env.put(Context.SECURITY_CREDENTIALS,adminPassword);
    env.put("com.sun.jndi.ldap.connect.pool", "true");
    env.put("java.naming.ldap.attributes.binary","objectSID");

    try {
        env.put(Context.PROVIDER_URL, ldapURL);
        env.put("com.sun.jndi.ldap.netscape.schemaBugs", "true");
        DirContext ctx = new InitialDirContext(env);
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
       String searchFilter = "(&(objectClass=user)(cn=" + objectName +"))";
        String searchBase ="DC=ABCD,DC=CORP";
        int totalResults = 0;
        String returnedAtts[]={"cn","distinguishedName","objectSID"};
        searchControls.setReturningAttributes(returnedAtts);
        NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchControls);
        while (answer.hasMoreElements()) {
            SearchResult sr = (SearchResult)answer.next();
            Attributes attrs = sr.getAttributes();
            if (attrs != null) {                         
                try {
                    for (NamingEnumeration ae = attrs.getAll();ae.hasMore();) {
                        Attribute attr = (Attribute)ae.next();
                        System.out.println("CN :" +attrs.get("cn").get());
                        byte[] SID = (byte[])attrs.get("objectSID").get();
                        String strSID = getSIDasStringOfBytes(SID);
                        System.out.println("Object SID :" + strSID );
                        return strSID;
                    }

                }     
                catch (NamingException e)    {
                    System.err.println("Problem listing membership: " + e);
                    return "ERROR";
                }
                ctx.close();
            }
        }
                      
        } catch (NamingException ne) {
        ne.printStackTrace();
        System.out.println("Error: " + ne);
        return "ERROR";
        }
        return "ERROR";
}

public static String getSIDasStringOfBytes(byte[] sid) {
    String strSID = "";
    int version;
    long authority;
    int count;
    String rid = "";
    strSID = "S";

     // get version
    version = sid[0];
    strSID = strSID + "-" + Integer.toString(version);
    for (int i=6; i>0; i--) {
        rid += byte2hex(sid[i]);
    }

    // get authority
    authority = Long.parseLong(rid);
    strSID = strSID + "-" + Long.toString(authority);

    //next byte is the count of sub-authorities
    count = sid[7]&0xFF;

    //iterate all the sub-auths
    for (int i=0;i<count;i++) {
        rid = "";
        for (int j=11; j>7; j--) {
            rid += byte2hex(sid[j+(i*4)]);
        }
        strSID = strSID + "-" + Long.parseLong(rid,16);
    }
    return strSID;    
}

public static String byte2hex(byte b) {
String ret = Integer.toHexString((int)b&0xFF);
if (ret.length()<2) ret = "0"+ret;
return ret;
}

public static void main(String[] args) throws IOException {
//Search Filter is "CN"
getObjectSID("Rakesh K");
System.out.println("It's Done");
}

}

No comments:

Post a Comment