As organizations increasingly rely on cloud services, managing application secrets securely becomes crucial. Secrets, such as API keys and authentication credentials, can easily become vulnerabilities if not monitored properly. To address this need, we can utilize PowerShell to automate the process of retrieving and reporting on application secret expiration in Microsoft Azure Active Directory (Azure AD). This blog post outlines a PowerShell script that accomplishes just that.
You can use this repository link to access the whole script and Terraform code needed to construct the resource.
Overview of the Script ( Automation Accounts )
This PowerShell script connects to Microsoft Graph using app-only authentication, retrieves application registrations, checks their secret expiration dates, and generates a comprehensive HTML report. The report is then sent to a Logic App, which can be used for further processing, such as sending notifications to stakeholders.
Step-by-Step Breakdown of the Script
before we start let’s see what will receive as report :
1. Secure Credential Retrieval:
The script starts by retrieving the Application (Client) ID, Client Secret, and Tenant ID stored in Azure Automation as secure credentials. This ensures that sensitive information remains secure.
$ApplicationClientIddata = Get-AutomationPSCredential -Name 'ApplicationClientId'
2. Convert Secure Strings to Plain Text:
The retrieved secure strings are converted to plain text to facilitate their use in authentication.
$ApplicationClientId = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto( [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($ApplicationClientIddata.Password) )
3. Connecting to Microsoft Graph:
The script establishes a connection to Microsoft Graph using the provided credentials. This is essential for querying Azure AD for application registrations and their associated secrets.
Connect-MgGraph -TenantId $TenantId -ClientSecretCredential $ClientSecretCredential
4. Retrieving Application Registrations:
Once connected, the script retrieves all application registrations in Azure AD. Each application’s details, including its secrets, are then queried.
$Applications = Get-MgApplication -All
5. Secret Expiration Check:
The core of the script is a loop that checks the expiration status of each application’s secrets. It calculates how many days are left before each secret expires and categorizes them into three groups: expired, expiring soon (within 90 days), and still valid.
foreach ($Secret in $Secrets) { $RemainingDaysCount = ($EndDate - $Now).Days ... }
6. Generating an HTML Report:
The script constructs an HTML report summarizing the secret expiration status of all applications. It includes a summary of the total number of applications, counts of expired secrets, and a detailed table displaying individual application details.
$HtmlContent += @" <h3>Summary</h3> ... "@
7. Sending the Report to Logic App:
Finally, the generated HTML content is converted to JSON and sent to a specified Logic App endpoint for further processing, such as notifications or storage.
$Response = Invoke-RestMethod -Uri $LogicAppUrl -Method Post -Body $JsonPayload -ContentType 'application/json'
Benefits of This Script
– Automated Monitoring: By automating the secret expiration checks, organizations can proactively manage application secrets, reducing the risk of security breaches.
– Clear Reporting: The HTML report provides a visually accessible summary of application secret statuses, making it easier for teams to monitor compliance and identify issues.
– Integration with Azure Services: By sending reports to Logic Apps, the script can easily integrate with other Azure services for alerts or workflows, enhancing operational efficiency.
Overview of the Logic App
The main goal of the logic app for now is the receive the results and send email to certain users .
In the future this will be updated even to send chat in teams and another communication services
{ "definition": { "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#", "contentVersion": "1.0.0.0", "triggers": { "When_a_HTTP_request_is_received": { "type": "Request", "kind": "Http", "inputs": { "schema": { "properties": { "htmlContent": { "type": "string" } }, "type": "object" } } } }, "actions": { "Send_an_email_(V2)": { "type": "ApiConnection", "inputs": { "host": { "connection": { "name": "@parameters('$connections')['office365']['connectionId']" } }, "method": "post", "body": { "To": "ben_alaya_achraf@outlook.com", "Subject": "updates", "Body": "<p class=\"editor-paragraph\">@{triggerBody()?['htmlContent']}</p>", "Importance": "Normal" }, "path": "/v2/Mail" }, "runAfter": {} } }, "parameters": { "$connections": { "type": "Object", "defaultValue": {} } } }, "parameters": { "$connections": { "value": { "office365": { "id": "/subscriptions/subid/providers/Microsoft.Web/locations/francecentral/managedApis/office365", "connectionId": "/subscriptions/subid/resourceGroups/rg-app-registration-001/providers/Microsoft.Web/connections/office365", "connectionName": "office365" } } } } }
Terraform
resource "azurerm_automation_account" "automation-account" { name = "cloudopsmonitoring-poc-001" location = azurerm_resource_group.inframonitor_prd_rg.location resource_group_name = azurerm_resource_group.inframonitor_prd_rg.name sku_name = "Basic" } resource "azurerm_logic_app_workflow" "monitoringspn-logic_app_workflow" { name = "logic-monitor-poc-001" location = azurerm_resource_group.inframonitor_prd_rg.location resource_group_name = azurerm_resource_group.inframonitor_prd_rg.name lifecycle { ignore_changes = [ parameters, workflow_parameters ] } } resource "azurerm_resource_group" "inframonitor_prd_rg" { name = "rg-monitor-poc-001" location = "francentral" }
Conclusion
In conclusion, managing application secrets is vital for maintaining security in cloud environments. This PowerShell script provides a robust solution for monitoring secret expiration in Azure AD and generates actionable reports that can help organizations stay ahead of potential security issues. By leveraging automation and Azure services, teams can enhance their security posture while saving time and resources.
Ps : This will be udpates in the future to add the below feature :
- Scan Certificates too and add to the report
- Send Report to teams chat