c# How to install cert to remote computer and get all certs from store of remote computer

using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;

namespace ServiceCACryptLib
{
    public enum CertStoreName
    {
        MY,
        ROOT,
        TRUST,
        CA
    }
    public class CertStoreReader
    {

        #region P/Invoke Interop

        private static int CERT_STORE_PROV_SYSTEM = 10;
        private static int CERT_SYSTEM_STORE_CURRENT_USER = (1 << 16);
        private static int CERT_SYSTEM_STORE_LOCAL_MACHINE = (2 << 16);

        [DllImport("CRYPT32", EntryPoint = "CertOpenStore", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern IntPtr CertOpenStore(int storeProvider, int encodingType, int hcryptProv, int flags, string pvPara);

        [DllImport("CRYPT32", EntryPoint = "CertEnumCertificatesInStore", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern IntPtr CertEnumCertificatesInStore(IntPtr storeProvider, IntPtr prevCertContext);

        [DllImport("CRYPT32", EntryPoint = "CertCloseStore", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern bool CertCloseStore(IntPtr storeProvider, int flags);

        [DllImport("crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool CertAddCertificateContextToStore([In] IntPtr hCertStore, [In] IntPtr pCertContext, [In] uint dwAddDisposition, [In, Out] IntPtr ppStoreContext);

        [DllImport("Crypt32.dll", SetLastError = true)]
        public static extern IntPtr CertCreateCertificateContext(
            Int32 dwCertEncodingType,
            Byte[] pbCertEncoded,
            Int32 cbCertEncoded
        );

        public const Int32 X509_ASN_ENCODING = 0x00000001;

        public const Int32 PKCS_7_ASN_ENCODING = 0x00010000;

        public const Int32 MY_TYPE = PKCS_7_ASN_ENCODING | X509_ASN_ENCODING;

        const uint CERT_STORE_ADD_ALWAYS = 4;

        #endregion


        public string ComputerName { get; set; }

        private readonly bool isLocalMachine;
        public CertStoreReader(string machineName)
        {
            ComputerName = machineName;
            if (machineName == string.Empty)
            {
                isLocalMachine = true;
            }
            else
            {
                isLocalMachine = string.Compare(ComputerName, Environment.MachineName, true) == 0 ? true : false;
            }
        }

        public void InstallCert(CertStoreName storeName)
        {
            string fileName = "C:\\temp\\Test2.cer";

            var certificate = new X509Certificate(fileName);
            var certificateBytes = certificate.Export(X509ContentType.Cert);
            var certContextHandle = CertCreateCertificateContext(
                X509_ASN_ENCODING, certificateBytes, certificateBytes.Length);

            var givenStoreName = GetStoreName(storeName);

            if (givenStoreName == string.Empty)
                throw new Exception("Invalid Store Name");

            IntPtr storeHandle = IntPtr.Zero;
            try
            {
                storeHandle = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0, CERT_SYSTEM_STORE_LOCAL_MACHINE, string.Format(@"\\{0}\{1}", ComputerName, givenStoreName));

                if (storeHandle == IntPtr.Zero)
                    throw new Exception(string.Format("Cannot connect to remote machine: {0}", ComputerName));

                CertAddCertificateContextToStore(storeHandle, certContextHandle, CERT_STORE_ADD_ALWAYS, IntPtr.Zero);
                CertCloseStore(storeHandle, 0);
            }
            catch (Exception ex)
            {
                throw new Exception("Error opening Certificate Store", ex);
            }
            finally
            {
                if (storeHandle != IntPtr.Zero)
                    CertCloseStore(storeHandle, 0);
            }
        }

        public X509Certificate2Collection GetCertificates(CertStoreName storeName)
        {

            X509Certificate2Collection collectionToReturn = null;
            string givenStoreName = GetStoreName(storeName);

            if (givenStoreName == string.Empty)
            {
                throw new Exception("Invalid Store Name");
            }

            IntPtr storeHandle = IntPtr.Zero;

            try
            {
                storeHandle = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0, CERT_SYSTEM_STORE_LOCAL_MACHINE, string.Format(@"\\{0}\{1}", ComputerName, givenStoreName));
                if (storeHandle == IntPtr.Zero)
                {
                    throw new Exception(string.Format("Cannot connect to remote machine: {0}", ComputerName));
                }


                IntPtr currentCertContext = IntPtr.Zero;
                collectionToReturn = new X509Certificate2Collection();
                do
                {
                    currentCertContext = CertEnumCertificatesInStore(storeHandle, currentCertContext);
                    if (currentCertContext != IntPtr.Zero)
                    {
                        collectionToReturn.Add(new X509Certificate2(currentCertContext));
                    }
                }
                while (currentCertContext != (IntPtr)0);


            }
            catch (Exception ex)
            {
                throw new Exception("Error opening Certificate Store", ex);
            }
            finally
            {
                if (storeHandle != IntPtr.Zero)
                    CertCloseStore(storeHandle, 0);
            }

            return collectionToReturn;
        }

        private static string GetStoreName(CertStoreName certStoreName)
        {
            string storeName = string.Empty;
            switch (certStoreName)
            {
                case CertStoreName.MY:
                    storeName = "My";
                    break;

                case CertStoreName.ROOT:
                    storeName = "Root";
                    break;

                case CertStoreName.CA:
                    storeName = "CA";
                    break;

                case CertStoreName.TRUST:
                    storeName = "Trust";
                    break;
            }
            return storeName;
        }
    }
}

Open store remotly for specific user

CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
NULL, 
CERT_SYSTEM_STORE_USERS | CERT_STORE_READONLY_FLAG | CERT_STORE_OPEN_EXISTING_FLAG,
"\\\\computerName\\user_SID\\MY"))

How to get user sid
http://www.windows-commandline.com/get-sid-of-user/

2 comments:

  1. CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
    NULL,
    CERT_SYSTEM_STORE_USERS | CERT_STORE_READONLY_FLAG | CERT_STORE_OPEN_EXISTING_FLAG,
    "\\\\computerName\\user_SID\\MY"))
    How to get user sid
    http://www.windows-commandline.com/get-sid-of-user/


    not working with this..

    ReplyDelete
    Replies
    1. Provide more detailed comment then I can help you. "not working with this" is not a proper way how to ask question :)

      Delete