简体   繁体   中英

Query LDAP by userCertificate attribute, with certificate

I am getting the cert as byte[] such as:

byte[] certRaw;
X509certificate2 x509Cert = new x509Certificate2(Request.ClientCertificate.Certificate);
certRaw = x509Cert.GetRawCertData();

then I am trying to look up a user in LDAP by that value.

DirectorySearcher finduser = new DirectorySearcher(ldapconnection);
findUser.Filter = "(&(objectClass=user)(userCertificate=" + certRaw + "))";

This is not working to match the userCertificate in the LDAP. I am able to look up the user by the CN if I grab that off the cert and use it instead of the userCertificate attribute, but that is not the requirement I've been given. Any help is appreciated.

I was asked the same thing!

Well, I was asked "how can I find a user in Active Directory by the certificate published against them when all I have is the certificate, and the certificate doesn't necessarily have the user's subject name in it and might not be consistent with anything". So: close enough.

And I put your question together with another answer, and got something that looks like it works.

Usual disclaimers apply : Don't do this ... This might cripple your DCs, or be mildly carcinogenic, or something. Don't know how or whether it works with multiple certificates stuffed into userCertificate, so the query would likely need to be modified in that case.

To run this, you need a .CER file of the certificate you're searching for. Then it's

FindUserWithCert mycert.CER 

And you're away.

using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.DirectoryServices;

/// This is sample code only so please enjoy it with all care
/// and no responsibility :) 
/// 
namespace FindUserWithCert
{
    class Program

    {
        static void Main(string[] args)
        {
            byte[] certRaw; 
            X509Certificate2 x509Cert = new X509Certificate2(args[0]); 
            certRaw = x509Cert.GetRawCertData();

            string certBytes = "";

            foreach (byte b in certRaw){
                certBytes += String.Format("\\{0:X}", b);
                //Console.Write (String.Format("\\{0:X}",b));
            }

            DirectorySearcher findUser = new DirectorySearcher("(&(objectClass=user)(userCertificate=" + certBytes + "))");

            foreach (System.DirectoryServices.SearchResult thing in findUser.FindAll())
            {
                Console.WriteLine(thing.Path.ToString());
            }

        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM