Skip to main content

Security & Compliance

What You’ll Learn

By the end of this chapter, you’ll understand:
  • Security fundamentals - Why security matters and what the real costs of breaches are
  • Defense in Depth - Why one security layer isn’t enough (like having multiple locks on your door)
  • Zero Trust - Why you should “never trust, always verify” (even internal requests)
  • Azure Security Center - How to get a security score and fix vulnerabilities automatically
  • Azure Sentinel (SIEM) - How to detect hackers trying to break into your system
  • Key Vault - Where to store passwords safely (never in your code!)
  • Real-world security patterns - How to actually secure a production web application

Introduction: What is Security? (Start Here if You’re New)

Why Security Matters (Real Numbers)

Security = Protecting your application, data, and users from unauthorized access Think of it like protecting your house:
  • Locks on doors = Authentication (only you have the key)
  • Alarm system = Monitoring (alerts when someone breaks in)
  • Safe for valuables = Encryption (protects important items even if thieves get in)
  • Security cameras = Logging (records what happened)

The Cost of Poor Security (True Stories)

Example 1: Equifax Data Breach (2017)
  • What happened: Hackers stole personal data of 147 million people
  • How: Unpatched vulnerability in web application (known for 2 months, not fixed)
  • Cost:
    • Settlement: $700 million
    • Stock price drop: -35% ($6 billion in market value)
    • CEO resigned
  • Prevention cost: ~$50,000 (security scanning tools + patch deployment)
  • ROI of security: 14,000x
Example 2: Capital One Breach (2019)
  • What happened: Hacker accessed 100 million credit card applications
  • How: Misconfigured firewall on AWS (allowed access from internet)
  • Cost:
    • Fine: $80 million
    • Legal fees: $270 million
    • Reputation damage: Immeasurable
  • Prevention cost: ~$10,000 (proper firewall configuration + security audit)
  • ROI of security: 35,000x
Example 3: SolarWinds Supply Chain Attack (2020)
  • What happened: Hackers inserted malware into software updates, compromising 18,000 organizations
  • Cost: Estimated $90-100 billion in economic damage
  • Lesson: Trust no one (Zero Trust principle)

What “Security” Actually Means

Security is NOT a single thing. It’s multiple layers working together: 1. Authentication (“Who are you?”)
  • Prove your identity
  • Username + Password
  • Multi-Factor Authentication (MFA) = Password + Phone code
2. Authorization (“What can you do?”)
  • Even if you’re authenticated, you can only access what you’re allowed
  • Example: You can read files, but not delete them
3. Encryption (“Scramble data so hackers can’t read it”)
  • Data at rest: Files stored on disk (encrypted hard drive)
  • Data in transit: Files moving across network (HTTPS)
  • Example: Even if hacker steals database backup, they can’t read encrypted passwords
4. Monitoring (“Watch for suspicious activity”)
  • Someone trying 1,000 passwords = Brute force attack
  • User logging in from Russia and USA within 5 minutes = Impossible travel
  • Alert security team immediately!
5. Compliance (“Follow the rules”)
  • GDPR (Europe): Protect user privacy or pay €20 million fine
  • HIPAA (USA): Protect health records or go to jail
  • PCI DSS: Protect credit card data or lose ability to accept payments

Defense in Depth (The Castle Analogy)

Why One Security Layer Isn’t Enough

Medieval Castle Defense:
Cloud Application Defense (Same concept):
Real-World Example: Without Defense in Depth (Single firewall):
With Defense in Depth:

Zero Trust Architecture (Never Trust, Always Verify)

The Old Way (Castle-and-Moat Security) - BROKEN

Traditional Thinking:
  • “If you’re inside the company network, you’re trusted”
  • “Firewall keeps bad guys OUT, everyone INSIDE is safe”
Why it failed:
Real Example:
  • WannaCry ransomware (2017) infected one computer
  • Spread to 200,000 computers worldwide
  • Cost: $4 billion in damages
  • Why? Internal networks trusted each other blindly

The New Way (Zero Trust) - SECURE

Zero Trust Principles: 1. Verify Explicitly
  • NEVER trust anyone automatically
  • Always authenticate and authorize (even internal requests)
Example:
2. Use Least Privilege Access
  • Give users ONLY what they need (nothing more)
  • “Just-in-time” access (temporary permissions)
Example:
3. Assume Breach
  • Plan as if hackers are ALREADY inside your network
  • Minimize damage if compromised
Example:

Understanding Azure Security Tools

1. Azure Security Center (Your Security Dashboard)

Think of Security Center as your car’s dashboard:
  • Check Engine Light = Security alerts
  • Speedometer = Security Score (0-100%)
  • Maintenance Required = Recommendations to fix
What it does:
Cost:
  • Free tier: Basic security recommendations
  • Paid tier (Azure Defender): $15/server/month
    • Advanced threat protection
    • Just-in-time VM access
    • File integrity monitoring
    • Network traffic analysis
Real-World Example:

2. Azure Sentinel (Your Security Detective)

Azure Sentinel = Security Information and Event Management (SIEM) Think of Sentinel as a detective analyzing security camera footage: Without Sentinel (Manual investigation):
With Sentinel (Automated detection):
How Sentinel Works: Step 1: Collect logs (Data connectors)
  • Azure Activity Logs
  • Office 365 (email, SharePoint)
  • Firewall logs
  • Application logs
  • Third-party tools (AWS, Google Cloud, on-premises firewalls)
Step 2: Detect threats (Analytics rules)
  • Pre-built rules (Microsoft provides 200+ threat detection rules)
    • Brute force attacks (failed login attempts)
    • Crypto mining (unusual CPU usage + connections to mining pools)
    • Data exfiltration (large file uploads to external storage)
  • Custom rules (you write your own KQL queries)
Step 3: Investigate (Visual timelines)
  • See exactly what happened
  • Example: User A logged in → Accessed database → Downloaded 10 GB → Uploaded to external site
Step 4: Respond (Automated playbooks)
  • Automatic actions:
    • Block IP address
    • Disable user account
    • Isolate VM from network
    • Send email/Slack notification to security team
Cost:
  • First 10 GB/day: FREE
  • After 10 GB: $2.76/GB/day
  • Typical small company: ~$200-500/month
  • Typical large company: ~$5,000-20,000/month
ROI: Average company saves $2.5 million per year by detecting breaches early (IBM Security Report 2023)

3. Azure Key Vault (Your Digital Safe)

Key Vault = Secure storage for secrets The Problem (Storing secrets in code): BAD CODE (Never do this!):
Real Example:
  • Uber breach (2016): API keys hardcoded in GitHub
  • Cost: $148 million fine
The Solution (Key Vault): GOOD CODE:
Cost Tip: Key Vault costs 0.03per10,000secretoperations.Foratypicalapplicationreading10secretsatstartup,thiscostslessthan0.03 per 10,000 secret operations. For a typical application reading 10 secrets at startup, this costs less than 0.01/month. Even at enterprise scale (millions of operations), Key Vault rarely exceeds 10/month.ThecostofNOTusingKeyVaultasinglecredentialleakaverages10/month. The cost of NOT using Key Vault -- a single credential leak -- averages 4.45 million per incident (IBM Cost of a Data Breach Report 2023). How it works:
Key Vault Benefits:
  1. Centralized secret management
    • One place to store all secrets (not scattered across 50 config files)
    • Update secret once → All apps use new value immediately
  2. Automatic secret rotation
    • Secrets expire every 90 days
    • Key Vault rotates automatically
    • Example: Database password changes automatically, apps don’t notice
  3. Audit logging
    • Who accessed which secret? When?
    • Example: “User X accessed StripeSecretKey at 3 AM on Sunday” → Suspicious!
Cost:
  • Standard tier: 0.03per10,000operations( 0.03 per 10,000 operations (~5-10/month for typical app)
  • Premium tier: $1/month per key (hardware security module - HSM)

Azure Defense in Depth

1. Defense in Depth

[!TIP] Jargon Alert: Zero Trust The security philosophy of “Never trust, always verify.” Just because a request came from “inside the building” (or VNet) doesn’t mean it’s safe. Every request requires authentication and authorization.
[!WARNING] Gotcha: Just-In-Time (JIT) VM Access JIT is great for security (closing ports when not in use), but it takes 1-2 minutes to request access and open the port. Do not use this for automated scripts that expect instant connections.

2. Azure Security Center

Security Center provides unified security management and threat protection.

Security Posture

Secure Score

Measure security posture (0-100%)
  • Recommendations with impact
  • Track improvements over time

Regulatory Compliance

Track compliance with standards:
  • PCI DSS
  • ISO 27001
  • HIPAA
  • SOC 2

Key Features


3. Azure Sentinel (SIEM)

Sentinel is Azure’s cloud-native SIEM for intelligent security analytics.

Data Sources

  • Azure Activity Logs
  • Office 365 Logs
  • Firewall Logs
  • Threat Intelligence
  • Custom Logs

Example Hunting Query


4. Key Vault

Key Vault manages secrets, keys, and certificates securely.
Common Pitfall: Developers often create one Key Vault for all environments (dev, staging, prod). This is dangerous — a developer debugging in dev might accidentally read production secrets. Best practice: one Key Vault per environment, with separate access policies.

5. Azure Policy

Azure Policy enforces organizational standards and compliance.

Example Policies

Practical Tip: The “Audit First” Pattern When rolling out a new policy, always follow this sequence:
  1. Deploy with effect audit (logs violations but does not block)
  2. Wait 2 weeks and review violations in the Policy Compliance dashboard
  3. Work with teams to fix existing non-compliant resources
  4. Switch to effect deny once existing violations are resolved
Skipping step 1 and going straight to deny will break existing deployments and CI/CD pipelines — your team will hate you, and they will find ways to work around the policy rather than comply with it.

6. Security Best Practices

Zero Trust

Never trust, always verify. Verify explicitly, least privilege, assume breach.

Encryption Everywhere

Data at rest, in transit, and in use. Customer-managed keys for sensitive data.

Network Isolation

Private endpoints, NSGs, Azure Firewall. No public IPs on backends.

Identity is Perimeter

MFA, Conditional Access, PIM. Azure AD for all authentication.

Monitor Everything

All logs to Log Analytics. Alerts on suspicious activity.

Incident Response

Have a plan, test regularly, document lessons learned.

7. Advanced Security Patterns

Web Application Firewall (WAF) Configuration

Azure WAF protects against OWASP Top 10 vulnerabilities. Available on Azure Front Door and Application Gateway.

WAF Policy with Custom Rules

Custom Rule: Block Traffic from Specific Countries

Custom Rule: Rate Limiting

[!WARNING] Gotcha: WAF False Positives OWASP rules might block legitimate requests (e.g., SQL keywords in user input). Always test in Detection Mode first, review logs, then switch to Prevention Mode. Create exclusions for known false positives.
Real-World Example: An API endpoint /search?query=SELECT * FROM products gets blocked by WAF because “SELECT” triggers SQL injection detection. Solution: Add exclusion for that specific query parameter.

DDoS Protection Strategies

Azure DDoS Protection Standard

DDoS Protection Tiers:

Monitoring DDoS Attacks

[!TIP] Best Practice: Multi-Layer DDoS Defense Combine Azure DDoS Protection (L3/L4) with Azure Front Door WAF (L7) for comprehensive protection. DDoS handles volumetric attacks; WAF handles application-layer attacks.

Zero Trust Implementation

Zero Trust Principles:
  1. Verify Explicitly - Always authenticate and authorize
  2. Use Least Privilege - Just-in-time and just-enough-access
  3. Assume Breach - Minimize blast radius and verify end-to-end encryption

Conditional Access Policies

Risk-Based Access with Identity Protection

Impossible Travel Detection:

Privileged Identity Management (PIM)

Problem: Admins have permanent elevated access. If their account is compromised, attacker has full control. Solution: Just-in-time (JIT) access. Admins activate privileges only when needed, with approval workflow.

Enable PIM for Azure Resources

Activation Workflow

Access Review:
[!WARNING] Gotcha: Emergency Access Account Always have a “break glass” account (excluded from MFA and Conditional Access) for emergencies. Store credentials in physical safe. Use Azure Monitor alerts if this account is ever used.

Threat Detection with Sentinel

Advanced Threat Detection Rules

Detect Crypto Mining:
Detect Credential Dumping (Mimikatz):
Detect Data Exfiltration:

Automated Response Playbooks


Network Security Deep Dive

Problem: Azure SQL, Storage, etc. have public endpoints. Even with firewall rules, they’re exposed to the internet. Solution: Private Endpoint maps PaaS services to a private IP in your VNet.
Result: myserver.database.windows.net now resolves to 10.0.2.5 (private IP) instead of public IP.

Azure Firewall Configuration

User Defined Routes (Force Tunneling)


Security Monitoring & Alerts

Critical Security Alerts


Security Checklist for Production

Before going live, ensure:
  • Identity: MFA enabled for all admin accounts
  • Identity: Conditional Access policies active (block legacy auth, require compliant devices)
  • Identity: PIM enabled for privileged roles (no standing access)
  • Network: No public IPs on backend VMs
  • Network: Private Endpoints for all PaaS services (SQL, Storage, Key Vault)
  • Network: Azure Firewall or NVA with forced tunneling
  • Network: NSGs on all subnets (deny all by default)
  • Application: WAF enabled on Front Door/App Gateway (Prevention mode)
  • Application: DDoS Protection Standard (for critical apps)
  • Application: All secrets in Key Vault (no config files)
  • Data: TDE enabled on databases
  • Data: Customer-Managed Keys (CMK) for sensitive data
  • Monitoring: All logs flowing to Log Analytics
  • Monitoring: Sentinel enabled with threat detection rules
  • Monitoring: Alerts for suspicious activity (failed sign-ins, admin actions, data exfiltration)
  • Compliance: Azure Policy enforcing standards (tagging, allowed regions, encryption)
  • Incident Response: Runbook documented and tested

8. Interview Questions

Beginner Level

Answer:
  • RBAC: Controls WHO can do what (User Alice can create VMs). Focus: User Actions.
  • Azure Policy: Controls WHAT can be created (VMs must be in East US). Focus: Resource Properties.
RBAC allows access; Policy limits what that access can generate.
Answer: To securely store and manage:
  1. Secrets (Passwords, Connection strings)
  2. Keys (Encryption keys)
  3. Certificates (SSL/TLS certs)
It decouples security material from application code.

Intermediate Level

Answer: A security strategy using multiple layers of defense, so if one fails, others provide protection. Layers: Physical -> Identity -> Networking -> Compute -> Application -> Data. Example: Even if a hacker gets past the Firewall (Network), they still need MFA (Identity) and Database encryption (Data).
Answer: Sentinel is a Cloud-Native SIEM (Security Information and Event Management) + SOAR (Security Orchestration, Automation, and Response).
  1. Collect: Ingests logs from everywhere (Azure, AWS, On-prem firewall).
  2. Detect: Uses AI/ML rules to find threat patterns (e.g., Impossible Travel).
  3. Investigate: Visualizes the attack timeline.
  4. Respond: Triggers automated playbooks (e.g., block IP, disable user).

Advanced Level

Answer:
  1. Front Door/WAF: Filter malicious traffic (SQLi, XSS) at the edge.
  2. DDoS Protection: Enable standard protection if critical.
  3. Network: Use VNet injection, deny all inbound except from WAF.
  4. Identity: Use Managed Identity for backend resources.
  5. Data: Encrypt SQL with TDE and CMK (Customer Managed Keys).
  6. Secrets: Store all secrets in Key Vault.
  7. Monitoring: Enable App Insights and Sentinel.

8. Key Takeaways

Zero Trust

Assume breach. Verify every request explicitly. Use least privilege access.

Azure Policy

Use Policy to enforce compliance (e.g., Tagging, Regions) and prevent configuration drift.

Centralized Security

Use Azure Security Center (Defender for Cloud) and Sentinel for a unified view of security posture.

Key Vault

Never store credentials in config files or code. Centralize them in Key Vault.

Defense in Depth

Layer security controls. Don’t rely on a single perimeter firewall.

Next Steps

Continue to Chapter 11

Master Azure DevOps, CI/CD pipelines, and Infrastructure as Code