Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell script to find currently bound expiring certificates in IIS

I am trying to get a working script to check for expiring SSL certificates in IIS. There are many similar entries with simply getting the list of expiring installed certificates but I need some extra logic.

I need to know all certificates expiring within x days that are A) currently bound to a website and B) that website must have a state of "Started"

I have certain information gathered (below) but I am having trouble correlating them so they only give me the expiring certs I need. To add to the complexity, I can't simply look for the site name in the CN in the subject of the certificates because there are many hundreds of certs installed and it is not uncommon for 1 or more older certificates for the same site to still be installed. That being said, they have the same subject. I will need to compare thumbprints but getting the thumbprint by simply specifying the site name is proving to be difficult.

Some of the code to gather various relevant details is as follows:

ActiveSites = get-website | where {$_.State -eq "Started"}
$DaysToExpiration = 7
$InstalledCerts = gci cert:\localmachine\my
$ExpiringCerts = $InstalledCerts | Where {(($_.NotAfter - (Get-Date)).Days) -lt $DaysToExpiration}
like image 576
Justin Talbott Avatar asked Apr 24 '13 01:04

Justin Talbott


1 Answers

A list of the certificates bound to websites can be obtained from the IIS: provider:

Get-ChildItem IIS:SSLBindings

Try this:

$DaysToExpiration = 7

$expirationDate = (Get-Date).AddDays($DaysToExpiration)

$sites = Get-Website | ? { $_.State -eq "Started" } | % { $_.Name }
$certs = Get-ChildItem IIS:SSLBindings | ? {
           $sites -contains $_.Sites.Value
         } | % { $_.Thumbprint }

Get-ChildItem CERT:LocalMachine/My | ? {
  $certs -contains $_.Thumbprint -and $_.NotAfter -lt $expirationDate
}
like image 66
Ansgar Wiechers Avatar answered Sep 22 '22 14:09

Ansgar Wiechers