To fine Expiry SSL Cert details script

 <#

Script : Suresh with Owners.ps1

Support : knvhsuresh@hotmail.com

Description : Script retrieves AAD Enterprise Application information, determines if the credential has expired, is near expiration or is still valid.

    Script will send an email via SendGrid API to credential owners informing them if the credential is expired or is near expiration.

    Current timeframe has been hard coded for nearing expiratiion or has expired is set to 90 Days.

#>



#Sets Variables used for AAD Enterprise Application queries

$credsInventory = @()

$status = @{}

$path = "AppsWithCredentials-" + (Get-Date).ToString("MMddyyyy") + ".csv"


#SendGrid API information for sending emails

<#

Param(

    [Parameter(Mandatory=$true)]

    [String]$devopsMailAPI

)

#>


#Creates function to sort credentials after initial Azure AD Query

Function Sort-Credentials ($App, $Creds, $Owner, $CredsType)

{

    if((Get-Date) -gt $($creds.EndDate))

    {

        $Status = "Expired"

    }

    else

    {

        $status = "Active"

    }


    $output += [PSCustomObject] @{

        Name = $app.DisplayName

        ObjectId = $app.ObjectId

        AppId = $app.AppId

        Crendentials = $credsType

        Start = ($creds.StartDate).ToString("MM/dd/yyyy")

        End = ($creds.EndDate).ToString("MM/dd/yyyy")

        Owner = $owner.DisplayName

        Publisher = $owner.PublisherName

        Contact  = $owner.UserPrincipalName

        Status = $Status


    }


    return $output

}


#----------------------------------------------------------[Execution]----------------------------------------------------------

#AAD Authentication Step - Needs work to verfiy

<#

try

{

    ## Authentication

    Write-Output ""

    Write-Output "------------------------ Authentication ------------------------"

    Write-Output "Logging in to Azure and Azure AD ..."


    $Conn = Get-AutomationConnection -Name AzureRunAsConnection

    

    $null = Connect-AzureAD `

                    -TenantId $Conn.TenantID `

                    -ApplicationId $Conn.ApplicationID `

                    -CertificateThumbprint $Conn.CertificateThumbprint


    # Ensures you do not inherit an AzContext in your runbook

    $null = Disable-AzContextAutosave -Scope Process

    

    $null = Connect-AzAccount `

                    -ServicePrincipal `

                    -Tenant $Conn.TenantID `

                    -ApplicationId $Conn.ApplicationID `

                    -CertificateThumbprint $Conn.CertificateThumbprint


    Write-Output "Successfully logged in to Azure and Azure AD." 

catch

{

    if (!$Conn)

    {

        $ErrorMessage = "Service principal not found."

        throw $ErrorMessage

    } 

    else

    {

        Write-Error -Message $_.Exception

        throw $_.Exception

    }

}

## End of authentication

#>


## Get all Azure AD applications

try

{

    Write-Output ""

    Write-Output "------------------------ Status ------------------------"

    Write-Output "Getting all Azure AD applications ..."


    $apps = Get-AzureADApplication -All $true

    

    

    Write-Output "Done."

    Write-Output "Formatting output ..."

}

catch

{

    if (!$apps)

    {

        Write-Error "No applications found."

    }

    else

    {

        Write-Error -Message $_.Exception

        throw $_.Exception

    }

}



## Extract information from each application

try

{

    foreach ($app in $apps)

    {                                                                                                                                                                                                                                                                                    

        $owner = Get-AzureADApplicationOwner -ObjectId $app.ObjectId


        if ($app.KeyCredentials)

        {

            foreach ($creds in $app.KeyCredentials)

            {

                $credsInventory += Sort-Credentials -App $app -Creds $creds -Owner $owner -CredsType "Certificate"

            } 

        }


        if ($app.PasswordCredentials)

        {

            foreach ($creds in $app.PasswordCredentials)

            {

                $credsInventory += Sort-Credentials -App $app -Creds $creds -Owner $owner -CredsType "Client secret"

            } 

        }

    }


    Write-Output "Done."

}

catch

{

    Write-Error -Message $_.Exception

    throw $_.Exception    

}


##Reviews each credential and updates the status filed to one of 3 values, Expired, ExpiringSoon, Valid

$ExpiresInDays = 90

$today = (Get-Date).ToUniversalTime()

$limitDate = $today.AddDays($ExpiresInDays)

$credsInventory | Sort-Object End | % {

        if($_.End -lt $today) {

            $_ | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'Expired' -Force

        } elseif ($_.End -le $limitDate) {

            $_ | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'ExpiringSoon' -Force

        } else {

            $_ | Add-Member -MemberType NoteProperty -Name 'Status' -Value 'Valid' -Force

        }

}


##Exports file to Storage account, if one is specified, and displays all Apps found

<#

try

{

    Write-Output "Listing all applications with credentials ..."


    $credsInventory


    Write-Output "Done."


    <# Export to the specified storage account

    

    if (!(Get-AzStorageAccount -Name $StorageAccountName -ResourceGroupName $ResourceGroupName -ErrorAction SilentlyContinue))

    {

        $storageAccount = New-AzStorageAccount -ResourceGroupName $ResourceGroupName -Name $StorageAccountName -Location $Location -SkuName Standard_LRS -Kind StorageV2

        $ctx = $storageAccount.Context

    }

    else

    { 

        $storageAccountKey = (Get-AzStorageAccountKey -Name $StorageAccountName -ResourceGroupName $resourceGroupName).Value[0]

        $ctx = New-AzStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $storageAccountKey 

    }


    if(!(Get-AzStorageContainer -Name $containerName -Context $ctx -ErrorAction Silentlycontinue))

    {

        Write-Output "Creating container ..."


        $null = New-AzStorageContainer -Name $containerName -Context $ctx -Permission blob


        Write-Output "Done."

    }

    

    Write-Output "Exporting to CSV files ..."


    $credsInventory | Export-Csv -Path C:\temp\$path -NoTypeInformation -Delimiter ";"

    #$null = Set-AzStorageBlobContent -Container $containerName -File $path -Blob $path -Context $ctx -Force


    Write-Output "Done."

}

catch

{

    Write-Error -Message $_.Exception

    throw $_.Exception     

}

#>



##comments - Maybe update destination address to go to IIMS if no contact information is found to create iServe Request to Azure Ops


#Reviews AAD Apps if based on their status. If credential is "Valid", no email will be sent. If credential is "ExpiringSoon" or "Expired", email will be sent to contact owner, if one exists.

Foreach ($status in $credsInventory) {

if ($status.status -eq 'Valid') {

$status.name

Write-Host $status.ObjectID

Write-Host "Service Account Password has not expired"

    if($status.Contact -eq $null)

    {

    Write-Host "No Contact information"

    }

    else{

    Write-Host $status.contact

    }

}

else

{

    Write-Host $status.name

    Write-Host $status.ObjectID

    Write-Host "Service Account Password near expiration or has expired. Owning team to be contacted"

    if($status.Contact -eq $null)

    {

    Write-Host "No Contact information"

        <# Hardcode the API key of sendgrid. We need it in the header of the API call

    $SENDGRID_API_KEY = "$devopsMailAPI"

 

    #Create the headers for the API call

    $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"

    $headers.Add("Authorization", "Bearer " + $SENDGRID_API_KEY)

    $headers.Add("Content-Type", "application/json")

    #>

    # Parameters for sending the email

    $fromEmailAddress = "no-reply@mhc.com"

    $destEmailAddress = "DL-AZURE-OPS"


    #Add Service account name/information to Subject Line and Content of Email, if possible

    $subject = "Service Account Expiration Notification"

    $aName = $status.Name

    $aOid = $status.ObjectId

    $aAppid = $status.AppId

    $aCredt = $status.Crendentials

    $aEnd = $status.End

    $aOwner = $status.Owner

    $aContact = if ($status.Contact -eq $null){Write-Host "No Contact Information"}

    $aStatus = $status.Status

    $content = "Hi Team

    The following Service account is either expired or nearing expiration.

    No Contaction/owner information is presented. Please review and contact Credential owner


    App Name         $aName

    Object ID        $aOid

    App ID           $aAppid

    Credential Type  $aCredt

    Expiration Date  $aEnd

    Owner            $aOwner

    Contact          $aContact

    Current Status   $aStatus

        " 

 

    # Create a JSON message with the parameters from above

    $json = @{}

    $json.personalizations = [System.Collections.ArrayList]@(@{


    to = @(


    #Not use if sending to Credential owner

    @{email = $destEmailAddress  + '@molinahealthcare.com';name = $destEmailAddress}

    # Add additional email ID here as a hash like above

    #@{email = $status.Contact}

    );


    subject = $subject})


    $json.content = [System.Collections.ArrayList]@()

    $json.content += @{type = 'text/plain';value = $content}


    $json.from = @{}

    $json.from.email = 'no-reply@mhc.com'

    $json.from.name = 'Azure Devops'


    $json.reply_to = @{}

    $json.reply_to.email = 'no-reply@mhc.com'

    $json.reply_to.name = 'Azure Devops'


    # Convert the string into a real JSON-formatted string

    # Depth specifies how many levels of contained objects

    # are included in the JSON representation. The default

    # value is 2

    $bodyJson = $json | ConvertTo-Json -Depth 4

 

    # Call the SendGrid RESTful web service and pass the

    # headers and json message. More details about the 

    # webservice and the format of the JSON message go to

    # https://sendgrid.com/docs/api-reference/

    #$response = Invoke-RestMethod -Uri https://api.sendgrid.com/v3/mail/send -Method Post -Headers $headers -Body $bodyJson


    #Start-Sleep -Seconds 20

    #exit 1

    

    }

    else{

    Write-Host $status.contact

     

    <# Hardcode the API key of sendgrid. We need it in the header of the API call

    $SENDGRID_API_KEY = "$devopsMailAPI"

 

    #Create the headers for the API call

    $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"

    $headers.Add("Authorization", "Bearer " + $SENDGRID_API_KEY)

    $headers.Add("Content-Type", "application/json")

    #>

    # Parameters for sending the email

    $fromEmailAddress = "no-reply@mhc.com"

    $destEmailAddress = "$MailToAddress"


    #Add Service account name/information to Subject Line and Content of Email, if possible

    $subject = "Service Account Expiration Notification"

    $aName = $status.Name

    $aOid = $status.ObjectId

    $aAppid = $status.AppId

    $aCredt = $status.Crendentials

    $aEnd = $status.End

    $aOwner = $status.Owner

    $aContact = $status.Contact

    $aStatus = $status.Status

    $content = "Hi Team

    The following Service account is either expired or nearing expiration.


    App Name         $aName

    Object ID        $aOid

    App ID           $aAppid

    Credential Type  $aCredt

    Expiration Date  $aEnd

    Owner            $aOwner

    Contact          $aContact

    Current Status   $aStatus

        " 

 

    # Create a JSON message with the parameters from above

    $json = @{}

    $json.personalizations = [System.Collections.ArrayList]@(@{


    to = @(


    #Not used if sending to Credential owner

    #@{email = $destEmailAddress  + '@molinahealthcare.com';name = $destEmailAddress}

    # Add additional email ID here as a hash like above

    @{email = $status.Contact}

    );


    subject = $subject})


    $json.content = [System.Collections.ArrayList]@()

    $json.content += @{type = 'text/plain';value = $content}


    $json.from = @{}

    $json.from.email = 'no-reply@mhc.com'

    $json.from.name = 'Azure Devops'


    $json.reply_to = @{}

    $json.reply_to.email = 'no-reply@mhc.com'

    $json.reply_to.name = 'Azure Devops'


    # Convert the string into a real JSON-formatted string

    # Depth specifies how many levels of contained objects

    # are included in the JSON representation. The default

    # value is 2

    $bodyJson = $json | ConvertTo-Json -Depth 4

 

    # Call the SendGrid RESTful web service and pass the

    # headers and json message. More details about the 

    # webservice and the format of the JSON message go to

    # https://sendgrid.com/docs/api-reference/

    #$response = Invoke-RestMethod -Uri https://api.sendgrid.com/v3/mail/send -Method Post -Headers $headers -Body $bodyJson


    #Start-Sleep -Seconds 20

    #exit 1


    }


}

Pause

}


Comments

Popular posts from this blog

NetSH collection commands

Script for Host entry in remote servers