Guest User

SSL Checker - URL and Certificate Store

a guest
Feb 25th, 2016
368
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #This is a combination of the two scripts credited below, I simply integrated some reporting logic.
  2.  
  3. #Credits:
  4. #Boe Prox - https://mcpmag.com/articles/2014/11/04/expiring-certs-in-powershell.aspx
  5. #This guy - https://iamoffthebus.wordpress.com/2014/02/04/powershell-to-get-remote-websites-ssl-certificate-expiration/
  6.  
  7. #Check to see if existing results file exists, if so, delete.
  8. $checkrep = Test-Path ".\sslresults.txt"
  9. If ($checkrep -like "True") {
  10.   Remove-Item ".\sslresults.txt"
  11. }
  12. New-Item ".\sslresults.txt" -type file
  13.  
  14. #Script variables to determine expiration threshold, the number of milliseconds before moving onto the next URL, and the input file
  15. $minimumCertAgeDays = 60
  16. $timeoutMilliseconds = 10000
  17. $urls = Get-Content .\sslurl.txt
  18.  
  19. #Primary script function
  20. [Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
  21. foreach ($url in $urls)
  22. {
  23.     Write-Host Checking $url -f Red
  24.     $req = [Net.HttpWebRequest]::Create($url)
  25.     $req.Timeout = $timeoutMilliseconds
  26.     try {$req.GetResponse() |Out-Null} catch { Write-Host Exception while checking URL $url`: $_ -f Red}
  27.     [datetime]$expiration = $req.ServicePoint.Certificate.GetExpirationDateString()
  28.     [int]$certExpiresIn = ($expiration - $(get-date)).Days
  29.     $certName = $req.ServicePoint.Certificate.GetName()
  30.     $certPublicKeyString = $req.ServicePoint.Certificate.GetPublicKeyString()
  31.     $certSerialNumber = $req.ServicePoint.Certificate.GetSerialNumberString()
  32.     $certThumbprint = $req.ServicePoint.Certificate.GetCertHashString()
  33.     $certEffectiveDate = $req.ServicePoint.Certificate.GetEffectiveDateString()
  34.     $certIssuer = $req.ServicePoint.Certificate.GetIssuerName()
  35.  
  36. ##Report Logic
  37. #If the URL does not exist, it will return a value to the script saying that -736010 days remain.  This logic specifically marks that item and moves on.
  38.     if ($certExpiresIn -le -736010)
  39.     {
  40.         {Write-Host $url does not exist. -f Yellow}
  41.         $output = "$url does not exist or is not responding.`r`n"
  42.         Out-File -filepath .\sslresults.txt -inputobject $output -encoding ASCII -width 50 -Append
  43.     }  
  44. #If the URL is less than the number of acceptable expiration days but more than 0, the script will send a warning.
  45.     if ($certExpiresIn -le $minimumCertAgeDays -and $certExpiresIn -gt 0)
  46.     {
  47.         {Write-Host Cert for site $url expires in $certExpiresIn days [on $expiration] -f Green}
  48.         $output = "Notice - CERTIFICATE EXPIRING SOON - Cert for site $url expires in $certExpiresIn days [on $expiration].  Threshold is $minimumCertAgeDays days.`r`n"
  49.         Out-File -filepath .\sslresults.txt -inputobject $output -encoding ASCII -width 50 -Append
  50.     }
  51. #If the URL has expired (less than 0 days remaining), the script will flag accordingly.
  52.     if ($certExpiresIn -lt 0 -and $certExpiresIn -gt -730160)
  53.     {
  54.         {Write-Host Cert for site $url expires in $certExpiresIn days [on $expiration] -f Green}
  55.         $output = "**EXPIRED CERTIFICATE DETECTED** - Cert for site $url expires in $certExpiresIn days [on $expiration].  Threshold is $minimumCertAgeDays days.`r`n"
  56.         Out-File -filepath .\sslresults.txt -inputobject $output -encoding ASCII -width 50 -Append
  57.     }
  58. #If the cert is above the threshold, the script will not write to the file.
  59.     else
  60.         {Write-Host Cert for site $url expires in $certExpiresIn days [on $expiration] -f Green}
  61.  
  62. #Uncomment this section for a full report that will show current, unexpired certificates#
  63. #        $output = "Cert for site $url expires in $certExpiresIn days [on $expiration].`r`n"
  64. #       Out-File -filepath .\sslresults.txt -inputobject $output -encoding ASCII -width 50 -Append
  65.    
  66. rv req
  67.     rv expiration
  68.     rv certExpiresIn
  69. }
  70.  
  71. Function Get-PKICertificates {
  72.  
  73. [cmdletbinding(  
  74.     DefaultParameterSetName = 'PKI'
  75. )]  
  76. param(  
  77.     [Parameter(  
  78.         Mandatory = $False,  
  79.         ParameterSetName = '',
  80.         HelpMessage = "Computer to query certificates.",  
  81.         ValueFromPipeline = $True)]  
  82.         [string[]]$Computer = $Env:Computername,
  83.     [Parameter(    
  84.         ParameterSetName = '',
  85.         HelpMessage = "Acceptable values are 'LocalMachine','CurrentUser'. `
  86.        CurrentUser can only be access on local machine. LocalMachine can be accessed on local or remote machine.",  
  87.         ValueFromPipeline = $False)]  
  88.         [string][ValidateSet("LocalMachine","CurrentUser")]
  89.         $StoreLocation = "LocalMachine",
  90.     [Parameter(  
  91.         ParameterSetName = '',  
  92.         HelpMessage = "Acceptable values are 'AddressBook','AuthRoot','CertificateAuthority','Disallowed','My',`
  93.        'Root','TrustedPeople','TrustedPublisher'",          
  94.         ValueFromPipeline = $False)]  
  95.         [string][ValidateSet("AddressBook","AuthRoot","CA","Disallowed","My","Root","TrustedPeople","TrustedPublisher")]
  96.         $StoreName = "My",  
  97.     [Parameter(  
  98.         Mandatory = $False,  
  99.         ParameterSetName = '',  
  100.         HelpMessage = "Acceptable values are 'ReadOnly','ReadWrite','MaxAllowed','OpenExistingOnly','IncludeArchived'",          
  101.         ValueFromPipeline = $False)]  
  102.         [string][ValidateSet("ReadOnly","ReadWrite","MaxAllowed","OpenExistingOnly","IncludeArchived")]$OpenFlag = "ReadOnly",
  103.     [Parameter(  
  104.         Mandatory = $False,  
  105.         ParameterSetName = 'Expired',
  106.         HelpMessage = "Show expired certificates",  
  107.         ValueFromPipeline = $False)]  
  108.         [switch]$ListExpired,
  109.     [Parameter(  
  110.         Mandatory = $False,  
  111.         ParameterSetName = 'Expiring',
  112.         HelpMessage = "Enter a number to list certificates expiring in given number of days",  
  113.         ValueFromPipeline = $False)]  
  114.         [Int32]$ExpiresIn        
  115. )
  116. Begin {
  117.     #Create variable that holds the OpenFlags object
  118.     Write-Verbose "Setting the OpenFlag variable"
  119.     $ro=[System.Security.Cryptography.X509Certificates.OpenFlags]"$OpenFlag"
  120.      
  121.     #Create variable that holds the Store Location object
  122.     Write-Verbose "Setting the Store Location variable"
  123.     $cu=[System.Security.Cryptography.X509Certificates.StoreLocation]"$StoreLocation"
  124.              
  125.     }  
  126. Process {
  127.     ForEach ($c in $computer) {
  128.         Try {
  129.             #Check to see if computer is remote or local
  130.             Write-Verbose "Checking to see if computer is local or remote."
  131.             If ($Env:Computername -ne $c) {
  132.                 Write-Verbose "Computer is remote, verifying network connection"
  133.                 If (!(Test-Connection -ComputerName $c -Count 1 -Quiet)) {
  134.                     Write-Verbose "$($c): Unable to locate computer"
  135.                     Continue
  136.                     }
  137.                 Else {
  138.                     If ($StoreLocation -eq "CurrentUser") {
  139.                         Write-Verbose "Attempting to access Remote Computer with CurrentUser store name."
  140.                         Write-Verbose "Unable to access remote computer's CurrentUser store. `
  141.                        `nYou can only do this with the LocalMachine store name."
  142.                         Continue
  143.                         }            
  144.                     }            
  145.                 }        
  146.             Switch ($StoreLocation) {
  147.                 LocalMachine {
  148.                     #Create new object and make connection to LocalMachine certificate store on computer
  149.                     Write-Verbose "Attempting to make connection to certificate store"
  150.                     $ce=new-object System.Security.Cryptography.X509Certificates.X509Store("\\$c\$StoreName",$cu)
  151.                     }
  152.                 CurrentUser {
  153.                     #Create new object and make connection to CurrentUser certificate store on computer
  154.                     Write-Verbose "Attempting to make connection to certificate store"
  155.                     $ce=new-object System.Security.Cryptography.X509Certificates.X509Store("$StoreName")
  156.                     }
  157.                 }                                            
  158.              
  159.             #Open the store using defined flags
  160.             Write-Verbose "Opening certificate store using defined OpenFlags"
  161.             $ce.Open($ro)
  162.              
  163.             #Determine what will be displayed based on parameter set name
  164.             Write-Verbose "Determining what certificates to display"
  165.             Switch ($Pscmdlet.ParameterSetName) {
  166.                 "PKI" {
  167.                     #List all certificates in the store
  168.                     Write-Verbose "Listing all certificates in store"
  169.                     $ce.certificates
  170.                     }
  171.                 "Expired" {
  172.                     Write-Verbose "Listing all expired certificates"
  173.                     $ce.Certificates | ? {$_.NotAfter -le (Get-Date)}
  174.                     }
  175.                 "Expiring" {
  176.                     Write-Verbose "Listing certificates that expire in $ExpiresIn days"
  177.                     #Create a datetime object with the expiration threshold to compare against certificate expiration timestamp
  178.                     $deadline = (Get-Date).AddDays($ExpiresIn)
  179.                     $ce.Certificates | ? {$_.NotAfter -le ($deadline)}
  180.                     }
  181.                 }                
  182.             }
  183.         Catch {        
  184.             #Write error that occurred with connection          
  185.             Write-Host -foregroundcolor Yellow "$($c): $($error[0])"
  186.             }
  187.         }
  188.     }          
  189. }
  190. $servers = get-content .\servers.txt    
  191. Function List{
  192. foreach ($server in $servers){
  193. Get-PKICertificates -comp $server -StoreLocation LocalMachine -StoreName My -ExpiresIn 60 | Format-Table @{Label=”Server Name”;Expression={($server)}},FriendlyName, @{Label=”Expires In (Days)”;Expression={($_.NotAfter – (get-Date)).Days}} -auto
  194. }
  195. }
  196. List | Out-File .\servercerts.txt
  197.  
  198. #Email Variables
  199. $date = Get-Date -Format "MMMM d, yyyy"
  200. $time = Get-Date -Format "hh:mmtt"
  201. $subject = "SSL Report - $Date - $Time"
  202. $body = Get-Content .\sslresults.txt
  203. $SMTPServer = "smtp.local"
  204. $sslresults = get-content .\sslresults.txt
  205. $cerstore = get-content .\servercerts.txt
  206.  
  207. #Mail action
  208. Send-MailMessage -from $from -to $to -subject $subject -body ($sslresults + $cerstore | out-string) -smtpserver $SMTPServer
Advertisement
Add Comment
Please, Sign In to add comment