########################## # Writer: Claudio Boggian # Company: PAL s.r.l. #------------------------- # Date: 2024/02/20 # v: 1.0 # Reason: Emission #------------------------- ########################## Param( [string] $ApplicationId = "", [string] $Secured = "", [string] $tenantID = "", [Int64] $warn = 30, [Int64] $crit = 15 ) if ("" -eq $ApplicationId){ Write-Host "First param - ApplicationId not set" -ForegroundColor red exit (2) } elseif ("" -eq $Secured){ Write-Host "Second param - SecuredId not set" -ForegroundColor red exit (2) } elseif ("" -eq $TenantID){ Write-Host "Third param - TenantID not set" -ForegroundColor red exit (2) } $ExitCode = 0 $SecuredPasswordPassword = ConvertTo-SecureString -String $Secured -AsPlainText -Force $ClientSecretCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ApplicationId, $SecuredPasswordPassword Connect-MgGraph -TenantId $tenantID -ClientSecretCredential $ClientSecretCredential -NoWelcome $Applications = Get-MgApplication -all $Logs = @() $ExpiredSecrets = @() $Res = @() foreach ($App in $Applications) { $AppName = $App.DisplayName $AppID = $App.Id $ApplID = $App.AppId if ($null -eq $AppID) { continue } $AppCreds = Get-MgApplication -ApplicationId $AppID | Select-Object PasswordCredentials, KeyCredentials $Secrets = $AppCreds.PasswordCredentials foreach ($Secret in $Secrets) { $StartDate = $Secret.StartDateTime $EndDate = $Secret.EndDateTime $SecretName = $Secret.DisplayName $RemainingDaysCount = ($EndDate - (Get-Date)).Days if($RemainingDaysCount -le $warn -and $RemainingDaysCount -ge 0){ $Logs += [PSCustomObject]@{ ApplicationName = $AppName ApplicationID = $ApplID SecretName = $SecretName SecretStartDate = $StartDate SecretEndDate = ($EndDate).ToString("dd/MM/yyyy") RemainingDaysCount = $RemainingDaysCount } } elseif ($null -ne $EndDate -and $RemainingDaysCount -lt -1) { $ExpiredSecrets += [PSCustomObject]@{ ApplicationName = $AppName EndDate = ($EndDate).ToString("dd/MM/yyyy") ApplicationID = $ApplID } } } } if ($Logs.Length -gt 0) { Write-Host 'WARN!' $Logs.Length ' Secret need attention!' } else { Write-Host 'OK! All secret are in range' } if ($ExpiredSecrets.Length -gt 0) { Write-Host $ExpiredSecrets.Length ' Secret expired!' Write-Host '' Write-Host 'Expired:' $ExpiredSecrets | Sort-Object -Property 'ApplicationName' | Format-Table } if ($Logs.Length -gt 0) { Write-Host 'Expiring:' Write-Host '' } foreach ($GLog in $Logs | Sort-Object -Property 'ApplicationName' | Group-Object -Property 'ApplicationName'){ Write-Host '/!\' $GLog.Name -ForegroundColor yellow foreach ($Log in $GLog.Group){ if ($null -ne $Log.SecretEndDate){ if ($Log.RemainingDaysCount -cle $crit) { $ExitCode = 2 } elseif($Log.RemainingDaysCount -cle $warn){ if($ExitCode -ne 2){ $ExitCode = 1 } } $Res = [PSCustomObject]@{ DaysLeft = $Log.RemainingDaysCount SecretName = $Log.SecretName EndDate = $Log.SecretEndDate } } } $Res | Format-Table } exit ($ExitCode)