Intel,Altiris Group

Expand all | Collapse all

Scripting In GSS To Remove Certificate From Local Computer | Personal | Certificate Store

  • 1.  Scripting In GSS To Remove Certificate From Local Computer | Personal | Certificate Store

    Posted Oct 06, 2015 02:51 PM

    Hello,

    I need to create a script (run from GSS) to remove a certificate from Local Computer | Personal | Certificate Store on a Windows 7 Machine.  Ive played around with a couple of ideas but it hasnt worked as yet.  Can anyone point me to the right script that would do this please.

    Many Thanks.



  • 2.  RE: Scripting In GSS To Remove Certificate From Local Computer | Personal | Certificate Store

    Posted Oct 06, 2015 03:21 PM

    Isn't this just a case of deleting the appropriate registry keys?



  • 3.  RE: Scripting In GSS To Remove Certificate From Local Computer | Personal | Certificate Store
    Best Answer

    Posted Oct 06, 2015 06:47 PM

    When I had to do this with about 4 hours warning on a Friday night after happy hour I had to target all machine certs with a custom template. After hacking together stuff from my own scripts and a very bad sample online I came up with the following. It's sloppy but it saved us from losing a third of our environment. If you're looking to delete based on cert template like us, locate and replace the text "Badly configured cert template", otherwise look a few lines up for a number of other variables you can use for criteria.

    Requirements:

    1. capicom.dll must be copied to C:\Windows\System32 and registered with regsvr32.exe prior to running the script. http://www.microsoft.com/en-us/download/details.aspx?id=25281

    2. CertMgr.Exe must be copied to C:\Windows\System32 prior to running the script. http://www.microsoft.com/en-us/download/details.aspx?id=8279

    3. The following vbscript MUST be executed under the local SYSTEM account for manipulating Machine certs, this is critical.

    On Error Resume Next 
     
    Dim ExtProp, certificatedata,Extension,EKU 
    Dim sho, fso, strcurrentdir, strsysfolder 
    Set sho = Wscript.CreateObject("Wscript.Shell") 
    Set FSO = CreateObject("Scripting.FileSystemObject") 
    Dim Store, Certificates, Certificate 
    Dim StrsubjectName(500), STRIssuerName(500), strTemplateName(500), strThumbPrint(500), strValidFrom(500), strValidTo(500), strDaysToExpire(500), i,j,k,g,m 
    Dim strEDUOID(500,500), StrFriendlyName(500,500) 
    Dim strDirectory, strFile, strText, intDeleted
    Dim objNTInfo, objTemplate
     
    strDirectory = "" 
    strFile = "C:\Windows\Packages\Logs\CertDelResult.txt"
    strCompliantFile = "C:\Windows\Packages\Logs\CertDelCompliant.txt"
     
    Const CAPICOM_LOCAL_MACHINE_STORE = 1 
    Const CAPICOM_CERTIFICATE_FIND_SUBJECT_NAME = 1 
    Const CAPICOM_STORE_OPEN_READ_ONLY = 0 
    Const CAPICOM_PROPID_FRIENDLY_NAME =11 
    Const CAPICOM_ENCODE_BINARY = 1 
     
    Set objFSO = CreateObject("Scripting.FileSystemObject") 
    Set Store = CreateObject("CAPICOM.Store") 
    Set objNTInfo = CreateObject("WinNTSystemInfo") 
     
    GetComputerName = Ucase(objNTInfo.ComputerName) 
     
     
    If objFSO.FileExists(strDirectory & strFile) Then 
    	Set objFolder = objFSO.GetFolder(strDirectory) 
    Else 
    	Set objFile = objFSO.CreateTextFile(strDirectory & strFile) 
    End If  
     
    Set objFile = Nothing 
    Set objFolder = Nothing 
     
    Const ForAppending = 8 
     
    Set objTextFile = objFSO.OpenTextFile _ 
    (strDirectory & strFile, ForAppending, True) 
      
    Store.Open CAPICOM_LOCAL_MACHINE_STORE, "MY" ,CAPICOM_STORE_OPEN_READ_ONLY 
    Set Certificates = Store.Certificates 
     
    If Certificates.Count > 0 Then
    intDeleted = 0
    	For Each Certificate in Certificates 
    		g=g+1 
    		Set objTemplate = Certificate.Template
    		strSubjectName(g) = Certificate.SubjectName 
    		strIssuerName(g) = Certificate.IssuerName 
    		strTemplateName(g) = objTemplate.Name
    		strThumbPrint(g) = Certificate.Thumbprint
    		strValidFrom(g) = Certificate.ValidFromDate 
    		strValidTo(g) = Certificate.ValidToDate 
    		strDaysToExpire(g) = DateDiff("d",now(),Certificate.ValidToDate) 
    
    		strText = strSubjectName(g) & chr(13) & chr(10) & _
    				strIssuerName(g) & chr(13) & chr(10) & _
    				strTemplateName(g) & chr(13) & chr(10) & _
    				strThumbPrint(g) & chr(13) & chr(10) & _
    				strValidFrom(g) & chr(13) & chr(10) & _
    				strValidTo(g) & chr(13) & chr(10) & _
    				strDaysToExpire(g)
    				
    		objTextFile.WriteLine(GetComputerName & " " & strText)
    
    		If strTemplateName(g) = "Badly configured cert template" Then
    			strCommand = "certmgr.exe -del -c -s -r localmachine MY -sha1 " & strThumbPrint(g)
    			Set objExec = sho.Exec(strCommand) 
    			While objExec.Status = 0 
    				WScript.Sleep 100 
    			Wend
    			objTextFile.WriteLine(objExec.Status)
    			If objExec.Status = 1 Then intDeleted = intDeleted + 1
    		End If
    
    	Next 
    	If intDeleted > 0 Then
    		objTextFile.Close
    		Set objFile1 = objFSO.CreateTextFile(strDirectory & strCompliantFile)
    		Wscript.Quit(0)
    	Else
    		objTextFile.Close
    		Set objFile1 = objFSO.CreateTextFile(strDirectory & strCompliantFile)
    		Wscript.Quit(9)
    	End If
    End If
    objTextFile.Close
    Set objFile1 = objFSO.CreateTextFile(strDirectory & strCompliantFile)
    Wscript.Quit(9)
    

     



  • 4.  RE: Scripting In GSS To Remove Certificate From Local Computer | Personal | Certificate Store

    Posted Oct 07, 2015 03:14 AM

    Hi - I think Certutil will do it which is what I have been testing with but it seems to be able to delete from a date etc but I want to target a specifica certificate in a specific store.  Thats what Im struggling with so any thoughts would be useful.  

    Deleting a REG key will that remove the Cert attached to it?



  • 5.  RE: Scripting In GSS To Remove Certificate From Local Computer | Personal | Certificate Store
    Best Answer

    Trusted Advisor
    Posted Oct 07, 2015 04:08 AM

    First, it's important to note that when you fire up certmgr on a windows box and a UI appears, it is loading up certmgr.msc rather than certmgr.exe. Only certmgr.exe accepts the commandline switches to add/remove certificates, and swiches applied to the .msc version will simply be ignored.

    Certmgr.exe is part of the Windows SDK. On my machine where I''ve installed the SDK on, it can be found in,

      C:\Program Files (x86)\Windows Kits\10\bin\x86

    This means that in order to use certmgr.exe on your computers in a GSS job, you'll need to copy this executable first to the target machine before running any script to add or remove certificates. 

     

    Install Certificate Command Line

    When I install a certifical to the localmachine personal store with certmgr I'll use a command like,

    certmgr.exe -add c:\certs\mycert.cer -s -r localMachine personal
    

    Removing Certificate Command Line

    When removing a certificate, you'll have to know the name of the certificate as seen in the store itself. This may differ from the .cer filename.

    certmgr -del -c -n "<Certificate Name>" -s -r localmachine personal
    

     



  • 6.  RE: Scripting In GSS To Remove Certificate From Local Computer | Personal | Certificate Store
    Best Answer

    Posted Oct 07, 2015 04:26 AM

    I've been using a PS1 to achive this in the past when facing something similar. Maybe the below will help you further? In brief, the below checks for 3 possible names (we run multiple domains) and if found, removes the certificate from the machine's store. Note the RetVal variable is used to exit the script with a specific error code so we know exactly what happened and what the result was.

    The task sequence looks like:

    1. Copy the PS1 to the client

    2. Change the PS environment to RemoteSigned

    3. execute the PS1 using a command line like powershell -STA C:\Temp\DeleteMachineCertificate.PS1

    4. Reset the PS environment and delete the PS1

    ----------------------------------------------------------------------------------------------------------

    $computer = gc env:computername
    $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My","LocalMachine")
    $store.Open("ReadWrite")
    $store.Certificates
    $RetVal = 10050
    foreach($certLong in Get-ChildItem cert:\localmachine\My)
    {
        IF ($certLong.Subject -match "CN=$computer.domain.abc.com," -Or $certLong.Subject -match "CN=$computer.domain.def.com," -Or $certLong.Subject -match "CN=$computer.domain.ghi.com,")
        {
            $RetVal = 10052
            foreach($certShort in Get-ChildItem cert:\localmachine\My)
            {
                If ($certShort.Subject -match "CN=$computer,")
                {
                    $store.Remove($certShort)
                    $RetVal = 0
                }
            }
        }
    }
    $host.SetShouldExit($RetVal)



  • 7.  RE: Scripting In GSS To Remove Certificate From Local Computer | Personal | Certificate Store

    Posted Oct 07, 2015 05:03 AM

    Ive managed this now - thanks for all your help.  The issue was using the "MY" part to get the right store but it was simply this command:

    certutil -delstore MY <Certificate Name>

    This deleted the certifcate as I wanted.

    Thanks.



  • 8.  RE: Scripting In GSS To Remove Certificate From Local Computer | Personal | Certificate Store

    Trusted Advisor
    Posted Oct 07, 2015 05:07 AM

    Hi Ed,

    Agreed -kind of ;-)

    Like with many things Windows, it's often just a matter of manipulating files and the registry. The machine certs are stored as binary representations in blobs in a subkey somewhere under,

     HKLM\Software\Microsoft\SystemCertificates

    So it would be a case of finding the relevent key in here, and then deleting both it and the cert's binary representation (the 'blob') beneath. The key names are UIDs, which are handily taken from the cert thumbprints. That means that this seemingly random keyname will be the same for all machines you import the certificate to. 

    So, yes, knowing your cert thumprints means you can write some well-chosen reg delete commands in a script should remove the links to any cert you wish.  

    However, whilst this would be effective in killing your certificate of choice, I *suspect* it wouldn't be clean. Pretty sure (though open to correction) that other other files are created in the cert import process, rendering this a 'not-supported' MS route.

    So, unless there is a strong reason to use the registry hack, I'd tend towards using either certmgr.exe or something like the powershell script posted here (which I'd hope would initiate a full, clean cert removal).



  • 9.  RE: Scripting In GSS To Remove Certificate From Local Computer | Personal | Certificate Store

    Trusted Advisor
    Posted Oct 07, 2015 05:13 AM

    Are you sure that works? Certutil has a habit of reporting success for any rubbish you type into it... 

    Check your reg keys to be sure,

    HKLM\SOFTWARE\Microsoft\SystemCertificates\personal\Certificates

    If here there is a key named with the thumbprint of the certificate you have attempted to remove, then you can be sure that your removal didn't work.



  • 10.  RE: Scripting In GSS To Remove Certificate From Local Computer | Personal | Certificate Store

    Posted Oct 07, 2015 05:31 AM

    Ian - I think you missed the link to the powershell script.

    You are probably right about a hack no necessarily achieving a clean solution. I tend to use capture tools to find out what exact changes take place during certificate addition or removal and then assess whether a hack is viable.  However, the SDK utils are clearly the better route.



  • 11.  RE: Scripting In GSS To Remove Certificate From Local Computer | Personal | Certificate Store

    Posted Oct 07, 2015 05:31 AM

    Checking that it has gone.  Thanks.



  • 12.  RE: Scripting In GSS To Remove Certificate From Local Computer | Personal | Certificate Store

    Trusted Advisor
    Posted Oct 07, 2015 06:04 AM

    Hi Ed -thanks. Have edited the above to add the MSDN link (it's pretty much the same in fact as what BBC as posted further down).