Information Technology Grimoire

Version .0.0.1

IT Notes from various projects because I forget, and hopefully they help you too.

Expired Certificates

Certificate Expiration Checks

openssl: certificate expiration

openssl s_client -showcerts -servername 6holeocarina.com -connect 6holeocarina.com:443 <<< "Q" | openssl x509 -text | grep -iA2 "Validity"

Powershell: Find Expired Certificates

Get-ChildItem -Path cert:\* -Recurse -ExpiringInDays 0 
Get-ChildItem Cert:\LocalMachine\WebHosting -ExpiringInDays 30
Invoke-Command -ComputerName $remotecomputers {Get-ChildItem -Path cert:\* -Recurse -ExpiringInDays 0 }
Get-ChildItem -Recurse | where { $_.notafter -le (get-date).AddDays(75) } | select thumbprint, subject

Powershell: Check certificate expiration

[Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
$url = "https://www.microsoft.com/"
$req = [Net.HttpWebRequest]::Create($url)
$req.GetResponse() | Out-Null
$output = [PSCustomObject]@{
  URL = $url
  'Cert Start Date' = $req.ServicePoint.Certificate.GetEffectiveDateString()
  'Cert End Date' = $req.ServicePoint.Certificate.GetExpirationDateString()
}
$output

Powershell: Check certificate expiration (bulk)

$timeoutMilliseconds = 6000
$urls = @(
    "https://www.google.com/",
    "https://www.microsoft.com/"
)
 
# disabling the cert validation check. This is what makes this whole thing work with invalid certs...
[Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
 
foreach ($url in $urls) {
    Write-Host "Getting certificate information for $url ..." -ForegroundColor "Yellow"
    $req = [System.Net.WebRequest]::Create($url)
    $req.Timeout = $timeoutMilliseconds
 
    try {
        $req.GetResponse() | Out-Null
    }
    catch {
        Write-Host "Exception occurred while checking URL $url`: $_ ." -ForegroundColor "Red"
    }
    $expirationString = $req.ServicePoint.Certificate.GetExpirationDateString()
 
    $dateTimeFormat = "$((Get-Culture).DateTimeFormat.ShortDatePattern) $((Get-Culture).DateTimeFormat.LongTimePattern)"
    $expiration = [DateTime]::ParseExact($expirationString, $dateTimeFormat, [System.Globalization.DateTimeFormatInfo]::InvariantInfo, [System.Globalization.DateTimeStyles]::None)
 
    [int]$certExpiresIn = ($expiration - $(Get-Date)).Days
    if ($certExpiresIn -gt $minimumCertAgeDays){
        Write-Host "Certificate for site $url expires in $certExpiresIn days (on $('{0:dd.MM.yyyy.}' -f $expiration))." -ForegroundColor "Green"
    }
    else {
        Write-Host "ERROR: Certificate for site $url expires in $certExpiresIn days (on $('{0:dd.MM.yyyy.}' -f $expiration)) and query threshold is set to $minimumCertAgeDays days!" -ForegroundColor "Red"
    }
}