

Important Note: I cannot provide code for exploiting vulnerabilities, accessing secrets without authorization, or targeting specific organizations. This guide focuses on defensive security practices — detecting anomalies, securing Azure resources, rotating credentials, and incident response procedures.
| Tool/Account | Purpose | Version |
|---|---|---|
| Azure CLI | Manage Azure resources | ≥ 2.50.0 |
| Azure Subscription | Target environment | Any |
| Microsoft Entra ID (Azure AD) | Identity & access management | — |
| Python | Scripting & automation | ≥ 3.10 |
| Node.js | TypeScript/JavaScript tooling | ≥ 20 LTS |
| Git | Version control | ≥ 2.40 |
| VS Code / IDE | Development | Latest |
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Upgrade pip
pip install --upgrade pip
# Install Azure SDK packages (security-focused)
pip install \
azure-identity \
azure-mgmt-resource \
azure-mgmt-authorization \
azure-mgmt-monitor \
azure-mgmt-keyvault \
azure-keyvault-secrets \
azure-keyvault-keys \
azure-mgmt-security \
azure-mgmt-policyinsights \
python-dotenv \
rich \
tenacity \
pydantic \
pydantic-settings
# Initialize project
mkdir azure-security-hardening && cd azure-security-hardening
npm init -y
# Install dependencies
npm install \
@azure/identity \
@azure/arm-resources \
@azure/arm-authorization \
@azure/arm-monitor \
@azure/arm-keyvault \
@azure/keyvault-secrets \
@azure/keyvault-keys \
@azure/arm-security \
@azure/arm-policyinsights \
dotenv \
zod
# Dev dependencies
npm install -D typescript ts-node @types/node
# Initialize TypeScript
npx tsc --init --target ES2022 --module NodeNext --moduleResolution NodeNext --esModuleInterop --strict
"""
Azure Security Posture Assessment
Scans for common misconfigurations related to secret exposure,
overly permissive identities, and monitoring gaps.
"""
import os
import json
from dataclasses import dataclass, asdict
from typing import List, Optional
from datetime import datetime, timezone
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.authorization import AuthorizationManagementClient
from azure.mgmt.monitor import MonitorManagementClient
from azure.mgmt.keyvault import KeyVaultManagementClient
from azure.mgmt.security import SecurityCenter
from azure.keyvault.secrets import SecretClient
from azure.core.exceptions import HttpResponseError, ClientAuthenticationError
from rich.console import Console
from rich.table import Table
from rich.progress import Progress, SpinnerColumn, TextColumn
from pydantic import BaseModel, Field
from tenacity import retry, stop_after_attempt, wait_exponential
console = Console()
# ============================================================
# Configuration Models
# ============================================================
class AzureConfig(BaseModel):
subscription_id: str = Field(..., description="Azure Subscription ID")
tenant_id: Optional[str] = Field(None, description="Microsoft Entra Tenant ID")
use_managed_identity: bool = Field(False, description="Use Managed Identity for auth")
class Finding(BaseModel):
severity: str # CRITICAL, HIGH, MEDIUM, LOW, INFO
category: str
resource_id: str
resource_name: str
description: str
recommendation: str
reference_url: Optional[str] = None
# ============================================================
# Authentication Helper
# ============================================================
def get_credential(config: AzureConfig):
"""Get appropriate credential based on environment."""
if config.use_managed_identity:
client_id = os.getenv("AZURE_CLIENT_ID")
return ManagedIdentityCredential(client_id=client_id) if client_id else ManagedIdentityCredential()
return DefaultAzureCredential(
exclude_environment_credential=False,
exclude_managed_identity_credential=False,
exclude_shared_token_cache_credential=True,
exclude_visual_studio_code_credential=False,
exclude_cli_credential=False,
)
# ============================================================
# Security Checks
# ============================================================
class SecurityScanner:
"""Main scanner orchestrating all security checks."""
def __init__(self, config: AzureConfig):
self.config = config
self.credential = get_credential(config)
self.findings: List[Finding] = []
# Initialize clients
self.resource_client = ResourceManagementClient(self.credential, config.subscription_id)
self.auth_client = AuthorizationManagementClient(self.credential, config.subscription_id)
self.monitor_client = MonitorManagementClient(self.credential, config.subscription_id)
self.kv_mgmt_client = KeyVaultManagementClient(self.credential, config.subscription_id)
self.security_client = SecurityCenter(self.credential, config.subscription_id)
def add_finding(self, finding: Finding):
self.findings.append(finding)
# ---- Check 1: Key Vault Network Access & Purge Protection ----
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
def check_key_vaults(self):
"""Check Key Vaults for public network access, purge protection, and soft delete."""
console.print("[bold cyan]Scanning Key Vaults...[/bold cyan]")
vaults = list(self.kv_mgmt_client.vaults.list())
for vault in vaults:
props = vault.properties
# Check public network access
if props.public_network_access == "Enabled":
self.add_finding(Finding(
severity="HIGH",
category="Key Vault Network Security",
resource_id=vault.id,
resource_name=vault.name,
description="Key Vault allows public network access. Should be restricted to private endpoints or selected networks.",
recommendation="Configure private endpoints and disable public network access. Use 'az keyvault update --name <name> --default-action Deny'.",
reference_url="https://learn.microsoft.com/azure/key-vault/general/network-security"
))
# Check purge protection
if not props.enable_purge_protection:
self.add_finding(Finding(
severity="MEDIUM",
category="Key Vault Data Protection",
resource_id=vault.id,
resource_name=vault.name,
description="Purge protection is disabled. Deleted vaults/secrets can be permanently destroyed.",
recommendation="Enable purge protection: 'az keyvault update --name <name> --enable-purge-protection true'.",
reference_url="https://learn.microsoft.com/azure/key-vault/general/soft-delete-overview"
))
# Check soft delete retention (should be ≥ 90 days)
if props.soft_delete_retention_in_days and props.soft_delete_retention_in_days < 90:
self.add_finding(Finding(
severity="MEDIUM",
category="Key Vault Data Protection",
resource_id=vault.id,
resource_name=vault.name,
description=f"Soft delete retention is {props.soft_delete_retention_in_days} days (recommended ≥ 90).",
recommendation="Set retention to 90+ days: 'az keyvault update --name <name> --retention-days 90'.",
))
# ---- Check 2: Role Assignments - Overly Permissive ----
def check_role_assignments(self):
"""Identify risky role assignments (Owner, Contributor, User Access Admin at subscription/RG level)."""
console.print("[bold cyan]Scanning Role Assignments...[/bold cyan]")
risky_roles = {
"Owner": "8e3af657-a8ff-443c-a75c-2fe8c4bcb635",
"Contributor": "b24988ac-6180-42a0-ab88-20f7382dd24c",
"User Access Administrator": "18d7d88d-d35e-4fb5-a5c3-7773c20a72d9",
}
# Check subscription scope
assignments = self.auth_client.role_assignments.list_for_subscription()
for assignment in assignments:
role_def_id = assignment.role_definition_id.split("/")[-1] if assignment.role_definition_id else ""
role_name = next((name for name, rid in risky_roles.items() if rid == role_def_id), None)
if role_name and assignment.scope and ("/subscriptions/" in assignment.scope or "/resourceGroups/" in assignment.scope):
principal_type = "Service Principal" if assignment.principal_type == "ServicePrincipal" else assignment.principal_type
self.add_finding(Finding(
severity="HIGH" if role_name in ["Owner", "User Access Administrator"] else "MEDIUM",
category="Identity & Access Management",
resource_id=assignment.id,
resource_name=f"{role_name} assignment to {principal_type}",
description=f"{role_name} role assigned at {assignment.scope} to {principal_type} ({assignment.principal_id})",
recommendation=f"Review and apply least privilege. Replace with custom roles or built-in roles like 'Reader', 'Key Vault Secrets User', etc.",
reference_url="https://learn.microsoft.com/azure/role-based-access-control/best-practices"
))
# ---- Check 3: Diagnostic Settings ----
def check_diagnostic_settings(self):
"""Verify diagnostic settings send logs to Log Analytics / Event Hub."""
console.print("[bold cyan]Scanning Diagnostic Settings...[/bold cyan]")
resources = self.resource_client.resources.list(
filter="resourceType eq 'Microsoft.KeyVault/vaults' or resourceType eq 'Microsoft.Storage/storageAccounts'"
)
for resource in resources:
try:
settings = self.monitor_client.diagnostic_settings.list(resource_id=resource.id)
has_log_analytics = any(
s.workspace_id for s in settings.value if s.logs and any(log.enabled for log in s.logs)
)
if not has_log_analytics:
self.add_finding(Finding(
severity="MEDIUM",
category="Monitoring & Logging",
resource_id=resource.id,
resource_name=resource.name,
description=f"No diagnostic settings sending logs to Log Analytics workspace for {resource.type}.",
recommendation="Configure diagnostic settings to send all logs to a central Log Analytics workspace.",
reference_url="https://learn.microsoft.com/azure/azure-monitor/essentials/diagnostic-settings"
))
except HttpResponseError as e:
console.print(f"[yellow]Warning: Could not check diagnostic settings for {resource.name}: {e}[/yellow]")
# ---- Check 4: Microsoft Defender for Cloud ----
def check_defender_for_cloud(self):
"""Check if Defender for Cloud plans are enabled."""
console.print("[bold cyan]Checking Microsoft Defender for Cloud...[/bold cyan]")
try:
pricings = self.security_client.pricings.list()
required_plans = ["VirtualMachines", "AppServices", "SqlServers", "StorageAccounts", "KeyVaults", "Containers", "Arm", "Dns", "KubernetesService"]
for plan in required_plans:
pricing = next((p for p in pricings if p.name == plan), None)
if not pricing or pricing.pricing_tier != "Standard":
self.add_finding(Finding(
severity="HIGH" if plan in ["KeyVaults", "SqlServers", "StorageAccounts"] else "MEDIUM",
category="Threat Protection",
resource_id=f"/subscriptions/{self.config.subscription_id}/providers/Microsoft.Security/pricings/{plan}",
resource_name=f"Defender for {plan}",
description=f"Microsoft Defender for {plan} is not enabled (Standard tier).",
recommendation=f"Enable Defender for {plan}: 'az security pricing create -n {plan} --tier Standard'.",
reference_url="https://learn.microsoft.com/azure/defender-for-cloud/defender-for-cloud-introduction"
))
except HttpResponseError as e:
console.print(f"[yellow]Warning: Could not check Defender plans: {e}[/yellow]")
# ---- Check 5: Policy Compliance ----
def check_policy_compliance(self):
"""Check for non-compliant resources against security policies."""
console.print("[bold cyan]Checking Policy Compliance...[/bold cyan]")
try:
from azure.mgmt.policyinsights import PolicyInsightsClient
policy_client = PolicyInsightsClient(self.credential, self.config.subscription_id)
# Query for non-compliant resources (simplified)
query_options = {
"filter": "IsCompliant eq false and PolicyDefinitionReferenceId eq 'Microsoft.KeyVault'",
"apply": "groupby((ResourceId, PolicyDefinitionId))",
}
# Note: Full policy insights requires more complex queries
console.print("[dim]Policy compliance check requires Policy Insights API - see production checklist[/dim]")
except ImportError:
console.print("[yellow]Policy Insights client not installed. Skipping.[/yellow]")
except Exception as e:
console.print(f"[yellow]Policy check failed: {e}[/yellow]")
# ---- Run All Checks ----
def run_all_checks(self):
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
) as progress:
tasks = [
progress.add_task("Key Vaults", total=None),
progress.add_task("Role Assignments", total=None),
progress.add_task("Diagnostic Settings", total=None),
progress.add_task("Defender for Cloud", total=None),
progress.add_task("Policy Compliance", total=None),
]
self.check_key_vaults()
progress.update(tasks[0], completed=True)
self.check_role_assignments()
progress.update(tasks[1], completed=True)
self.check_diagnostic_settings()
progress.update(tasks[2], completed=True)
self.check_defender_for_cloud()
progress.update(tasks[3], completed=True)
self.check_policy_compliance()
progress.update(tasks[4], completed=True)
def print_report(self):
"""Print findings as a formatted table."""
if not self.findings:
console.print("[bold green]✓ No security findings detected.[/bold green]")
return
# Sort by severity
severity_order = {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3, "INFO": 4}
self.findings.sort(key=lambda f: severity_order.get(f.severity, 5))
table = Table(title=f"Security Assessment Report - {datetime.now(timezone.utc).isoformat()}")
table.add_column("Severity", style="bold")
table.add_column("Category")
table.add_column("Resource")
table.add_column("Description")
table.add_column("Recommendation")
severity_colors = {
"CRITICAL": "red",
"HIGH": "red",
"MEDIUM": "yellow",
"LOW": "blue",
"INFO": "green",
}
for finding in self.findings:
color = severity_colors.get(finding.severity, "white")
table.add_row(
f"[{color}]{finding.severity}[/{color}]",
finding.category,
finding.resource_name,
finding.description[:80] + "..." if len(finding.description) > 80 else finding.description,
finding.recommendation[:80] + "..." if len(finding.recommendation) > 80 else finding.recommendation,
)
console.print(table)
console.print(f"\n[bold]Total Findings: {len(self.findings)}[/bold]")
for sev in ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"]:
count = sum(1 for f in self.findings if f.severity == sev)
if count:
console.print(f" {sev}: {count}")
def export_json(self, filepath: str):
"""Export findings to JSON for CI/CD integration."""
data = {
"scan_time": datetime.now(timezone.utc).isoformat(),
"subscription_id": self.config.subscription_id,
"findings": [asdict(f) for f in self.findings],
}
with open(filepath, "w") as f:
json.dump(data, f, indent=2)
console.print(f"[green]Report exported to {filepath}[/green]")
# ============================================================
# Main Entry Point
# ============================================================
def main():
import argparse
parser = argparse.ArgumentParser(description="Azure Security Posture Scanner")
parser.add_argument("--subscription-id", required=True, help="Azure Subscription ID")
parser.add_argument("--tenant-id", help="Microsoft Entra Tenant ID")
parser.add_argument("--managed-identity", action="store_true", help="Use Managed Identity")
parser.add_argument("--output", help="Export findings to JSON file")
args = parser.parse_args()
config = AzureConfig(
subscription_id=args.subscription_id,
tenant_id=args.tenant_id,
use_managed_identity=args.managed_identity,
)
scanner = SecurityScanner(config)
scanner.run_all_checks()
scanner.print_report()
if args.output:
scanner.export_json(args.output)
# Exit with non-zero if critical/high findings (useful for CI/CD)
critical_high = sum(1 for f in scanner.findings if f.severity in ["CRITICAL", "HIGH"])
if critical_high > 0:
console.print(f"\n[bold red]⚠ {critical_high} CRITICAL/HIGH findings detected![/bold red]")
exit(1)
if __name__ == "__main__":
main()
// secret-rotation.ts
// Automated Key Vault secret rotation with validation and audit logging
import {
DefaultAzureCredential,
ManagedIdentityCredential,
ClientSecretCredential,
} from "@azure/identity";
import { SecretClient } from "@azure/keyvault-secrets";
import { KeyClient } from "@azure/keyvault-keys";
import { KeyVaultManagementClient } from "@azure/arm-keyvault";
import { AuthorizationManagementClient } from "@azure/arm-authorization";
import { MonitorManagementClient } from "@azure/arm-monitor";
import { ResourceManagementClient } from "@azure/arm-resources";
import { z } from "zod";
import * as dotenv from "dotenv";
import crypto from "node:crypto";
dotenv.config();
// ============================================================
// Configuration & Validation
// ============================================================
const ConfigSchema = z.object({
subscriptionId: z.string().uuid(),
tenantId: z.string().uuid().optional(),
keyVaultName: z.string().min(3),
secretName: z.string().min(1),
rotationDays: z.number().int().positive().default(90),
useManagedIdentity: z.boolean().default(false),
clientId: z.string().uuid().optional(),
clientSecret: z.string().optional(),
logAnalyticsWorkspaceId: z.string().optional(),
});
type Config = z.infer<typeof ConfigSchema>;
function loadConfig(): Config {
const parsed = ConfigSchema.safeParse({
subscriptionId: process.env.AZURE_SUBSCRIPTION_ID,
tenantId: process.env.AZURE_TENANT_ID,
keyVaultName: process.env.KEY_VAULT_NAME,
secretName: process.env.SECRET_NAME,
rotationDays: parseInt(process.env.ROTATION_DAYS || "90", 10),
useManagedIdentity: process.env.USE_MANAGED_IDENTITY === "true",
clientId: process.env.AZURE_CLIENT_ID,
clientSecret: process.env.AZURE_CLIENT_SECRET,
logAnalyticsWorkspaceId: process.env.LOG_ANALYTICS_WORKSPACE_ID,
});
if (!parsed.success) {
console.error("❌ Configuration validation failed:");
console.error(parsed.error.flatten().fieldErrors);
process.exit(1);
}
return parsed.data;
}
// ============================================================
// Types
// ============================================================
interface RotationResult {
success: boolean;
secretName: string;
previousVersion?: string;
newVersion: string;
rotatedAt: string;
error?: string;
}
interface AuditLogEntry {
timestamp: string;
operation: "ROTATE_SECRET" | "VALIDATE_SECRET" | "ERROR";
secretName: string;
keyVaultName: string;
subscriptionId: string;
result: "SUCCESS" | "FAILURE";
details: Record<string, unknown>;
correlationId: string;
}
// ============================================================
// Credential Factory
// ============================================================
function createCredential(config: Config) {
if (config.useManagedIdentity) {
return config.clientId
? new ManagedIdentityCredential(config.clientId)
: new ManagedIdentityCredential();
}
if (config.clientId && config.clientSecret && config.tenantId) {
return new ClientSecretCredential(config.tenantId, config.clientId, config.clientSecret);
}
return new DefaultAzureCredential({
excludeSharedTokenCacheCredential: true,
excludeVisualStudioCodeCredential: false,
excludeCliCredential: false,
});
}
// ============================================================
// Audit Logging
// ============================================================
async function writeAuditLog(entry: AuditLogEntry, config: Config): Promise<void> {
// In production, send to Log Analytics, Event Hub, or SIEM
const logLine = JSON.stringify(entry);
console.log(`[AUDIT] ${logLine}`);
// Optional: Send to Log Analytics via Data Collector API
if (config.logAnalyticsWorkspaceId) {
// Implementation would use @azure/monitor-ingestion or direct HTTP
// See: https://learn.microsoft.com/azure/azure-monitor/logs/data-collector-api
}
}
// ============================================================
// Secret Generator
// ============================================================
function generateSecureSecret(length: number = 64): string {
// Use cryptographically secure random bytes
const bytes = crypto.randomBytes(length);
// Base64URL encode (no padding, URL-safe)
return bytes.toString("base64url");
}
function generateApiKey(prefix: string = "sk"): string {
const randomPart = crypto.randomBytes(32).toString("base64url");
return `${prefix}_${randomPart}`;
}
// ============================================================
// Rotation Logic
// ============================================================
class SecretRotator {
private secretClient: SecretClient;
private keyVaultUrl: string;
private config: Config;
private correlationId: string;
constructor(config: Config) {
this.config = config;
this.correlationId = crypto.randomUUID();
this.keyVaultUrl = `https://${config.keyVaultName}.vault.azure.net`;
const credential = createCredential(config);
this.secretClient = new SecretClient(this.keyVaultUrl, credential);
}
async getCurrentSecret(): Promise<{ value: string; version: string } | null> {
try {
const secret = await this.secretClient.getSecret(this.config.secretName);
return secret.value ? { value: secret.value, version: secret.properties.version || "unknown" } : null;
} catch (error: any) {
if (error.code === "SecretNotFound") {
return null;
}
throw error;
}
}
async rotateSecret(generator: "random" | "api-key" = "random"): Promise<RotationResult> {
const startTime = new Date().toISOString();
const current = await this.getCurrentSecret();
try {
// Generate new secret value
const newValue = generator === "api-key" ? generateApiKey() : generateSecureSecret();
// Set new secret version (Key Vault automatically versions)
const newSecret = await this.secretClient.setSecret(this.config.secretName, newValue, {
expiresOn: new Date(Date.now() + this.config.rotationDays * 24 * 60 * 60 * 1000),
tags: {
rotatedBy: "secret-rotation-automation",
rotatedAt: startTime,
correlationId: this.correlationId,
previousVersion: current?.version || "none",
},
});
const result: RotationResult = {
success: true,
secretName: this.config.secretName,
previousVersion: current?.version,
newVersion: newSecret.properties.version || "unknown",
rotatedAt: startTime,
};
await writeAuditLog(
{
timestamp: startTime,
operation: "ROTATE_SECRET",
secretName: this.config.secretName,
keyVaultName: this.config.keyVaultName,
subscriptionId: this.config.subscriptionId,
result: "SUCCESS",
details: {
previousVersion: current?.version,
newVersion: result.newVersion,
rotationDays: this.config.rotationDays,
},
correlationId: this.correlationId,
},
this.config
);
console.log(`✅ Secret rotated successfully: ${this.config.secretName} (v${result.newVersion})`);
return result;
} catch (error: any) {
const errorResult: RotationResult = {
success: false,
secretName: this.config.secretName,
newVersion: "failed",
rotatedAt: startTime,
error: error.message,
};
await writeAuditLog(
{
timestamp: startTime,
operation: "ROTATE_SECRET",
secretName: this.config.secretName,
keyVaultName: this.config.keyVaultName,
subscriptionId: this.config.subscriptionId,
result: "FAILURE",
details: { error: error.message },
correlationId: this.correlationId,
},
this.config
);
console.error(`❌ Rotation failed: ${error.message}`);
return errorResult;
}
}
async validateSecret(): Promise<boolean> {
const startTime = new Date().toISOString();
try {
const secret = await this.secretClient.getSecret(this.config.secretName);
const isValid = !!secret.value && secret.value.length > 0;
await writeAuditLog(
{
timestamp: startTime,
operation: "VALIDATE_SECRET",
secretName: this.config.secretName,
keyVaultName: this.config.keyVaultName,
subscriptionId: this.config.subscriptionId,
result: isValid ? "SUCCESS" : "FAILURE",
details: { version: secret.properties.version, hasValue: isValid },
correlationId: this.correlationId,
},
this.config
);
return isValid;
} catch (error: any) {
await writeAuditLog(
{
timestamp: startTime,
operation: "VALIDATE_SECRET",
secretName: this.config.secretName,
keyVaultName: this.config.keyVaultName,
subscriptionId: this.config.subscriptionId,
result: "FAILURE",
details: { error: error.message },
correlationId: this.correlationId,
},
this.config
);
return false;
}
}
async listSecretVersions(): Promise<void> {
console.log(`\n📋 Versions for ${this.config.secretName}:`);
for await (const version of this.secretClient.listPropertiesOfSecretVersions(this.config.secretName)) {
const tags = version.tags || {};
console.log(` v${version.version} | ${version.createdOn?.toISOString()} | ${tags.rotatedBy || "manual"} | ${tags.correlationId || "-"}`);
}
}
}
// ============================================================
// Main
// ============================================================
async function main() {
const config = loadConfig();
const rotator = new SecretRotator(config);
const args = process.argv.slice(2);
const command = args[0] || "rotate";
switch (command) {
case "rotate": {
const generator = args[1] === "apikey" ? "api-key" : "random";
const result = await rotator.rotateSecret(generator);
if (!result.success) process.exit(1);
break;
}
case "validate": {
const valid = await rotator.validateSecret();
console.log(valid ? "✅ Secret is valid" : "❌ Secret validation failed");
if (!valid) process.exit(1);
break;
}
case "list": {
await rotator.listSecretVersions();
break;
}
default:
console.error(`Unknown command: ${command}`);
console.log("Usage: ts-node secret-rotation.ts [rotate|validate|list] [apikey]");
process.exit(1);
}
}
main().catch((error) => {
console.error("Fatal error:", error);
process.exit(1);
});
.env)# .env - NEVER commit this file to version control
# Copy to .env.local and add to .gitignore
# Azure Authentication
AZURE_SUBSCRIPTION_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
AZURE_TENANT_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
# For Service Principal auth (CI/CD)
AZURE_CLIENT_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
AZURE_CLIENT_SECRET=your-client-secret-here
# For Managed Identity (Azure-hosted environments)
USE_MANAGED_IDENTITY=false
# Target Resources
KEY_VAULT_NAME=my-production-kv
SECRET_NAME=database-connection-string
ROTATION_DAYS=90
# Monitoring & Audit
LOG_ANALYTICS_WORKSPACE_ID=/subscriptions/.../resourceGroups/.../providers/Microsoft.OperationalInsights/workspaces/...
.github/workflows/security-scan.yml)name: Azure Security Posture Scan
on:
schedule:
- cron: "0 6 * * 1" # Weekly on Monday 06:00 UTC
workflow_dispatch:
pull_request:
branches: [main]
permissions:
id-token: write # For OIDC federation
contents: read
security-events: write # For SARIF upload
jobs:
security-scan:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: "pip"
- name: Install dependencies
run: |
pip install -r requirements.txt
- name: Azure Login (OIDC)
uses: azure/login@v2
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
- name: Run Security Scanner
id: scan
run: |
python security_scanner.py \
--subscription-id ${{ secrets.AZURE_SUBSCRIPTION_ID }} \
--managed-identity \
--output security-findings.json
- name: Upload Findings as Artifact
uses: actions/upload-artifact@v4
with:
name: security-findings
path: security-findings.json
retention-days: 30
- name: Comment on PR (if PR)
if: github.event_name == 'pull_request'
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const findings = JSON.parse(fs.readFileSync('security-findings.json', 'utf8'));
const criticalHigh = findings.findings.filter(f => ['CRITICAL','HIGH'].includes(f.severity)).length;
const body = `## 🔒 Azure Security Scan Results
- **Subscription**: ${findings.subscription_id}
- **Scan Time**: ${findings.scan_time}
- **Total Findings**: ${findings.findings.length}
- **Critical/High**: ${criticalHigh}
${criticalHigh > 0 ? '⚠️ **Action Required**: Review findings before merging.' : '✅ No critical/high findings.'}`;
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body
});
secret-rotation:
runs-on: ubuntu-latest
if: github.event_name == 'schedule' # Only on schedule
timeout-minutes: 15
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
cache: "npm"
- name: Install dependencies
run: npm ci
- name: Azure Login (OIDC)
uses: azure/login@v2
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
- name: Rotate Secrets
run: |
npx ts-node secret-rotation.ts rotate
env:
KEY_VAULT_NAME: ${{ secrets.KEY_VAULT_NAME }}
SECRET_NAME: ${{ secrets.SECRET_NAME }}
ROTATION_DAYS: "90"
// least-privilege-role.bicep
// Assigns minimal required roles instead of Cont
---
## Next Steps
1. **Get API Access** - Sign up at the official website
2. **Try the Examples** - Run the code snippets above
3. **Read the Docs** - Check official documentation
4. **Join Communities** - Discord, Reddit, GitHub discussions
5. **Experiment** - Build something cool!
## Further Reading
- [TechCrunch AI](https://techcrunch.com/category/artificial-intelligence/)
- [The Verge](https://www.theverge.com/technology)
- [Wired AI](https://www.wired.com/tag/artificial-intelligence/)
- [Medium AI](https://medium.com/topic/artificial-intelligence)
**Source:** [Security Week AI](https://www.securityweek.com/azure-flaw-exploited-to-target-secrets-at-norwegian-energy-firms/)
---
*Follow ICARAX for more AI insights and tutorials.*
