# Azure Security Project Lab

This is Azure basics to Advance security Lab project in different modules wise.

Overview

This project contains basics like perimeter as security to monitoring events, Threat Hunting using Microsoft CNAPP tools and SIEM and SOAR use cases. All labs and ARM/automation templates are as per my own lab performed, read instructions before using it.

{% hint style="info" %}
It contains both major and minor project. Major project means end to end implementation, Security Best Practices, Frameworks etc. And Minor project means Services Baseline implementation&#x20;
{% endhint %}

## <mark style="color:green;">Projects</mark>

<table data-view="cards"><thead><tr><th></th><th></th><th></th><th data-hidden data-card-cover data-type="files"></th></tr></thead><tbody><tr><td><mark style="color:purple;"><strong>Managing Resources inside Azure</strong></mark></td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Implementation of RBAC</strong></mark></td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Implementation of Network &#x26; Application Security</strong></mark></td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Implementation of Perimeter Security</strong></mark></td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Securing Storage Account &#x26; DB</strong></mark></td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Securing Secrets using Azure Key Vaults</strong></mark></td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Implementation Platform Protection</strong></mark></td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Implementation of Zero Trust Architecture</strong></mark></td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Managing Security Operations</strong></mark></td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Implementation of CSPM,CSWP,CNAPP,CWP</strong></mark></td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Implementation of SIEM and SOAR</strong></mark> </td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Detection and Threat Hunting</strong></mark></td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Posture &#x26; Vulnerability Management</strong></mark></td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Endpoint Security</strong></mark> </td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Threat Modelling</strong></mark></td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Integrate Security into the Development Process</strong></mark></td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Shift Left Approach</strong></mark></td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Securing DevOps CI/CD pipeline</strong></mark></td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Secrets Scanning using MDC</strong></mark> </td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>CASB implementation</strong></mark> </td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Implementation of MCRA</strong></mark></td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Implementation of Azure Security Benchmarks</strong></mark></td><td></td><td></td><td></td></tr><tr><td><mark style="color:purple;"><strong>Information Protection</strong></mark></td><td><ul><li>Microsoft Purview Intro</li><li>Data Life cycle </li><li>Data Loss Prevention (DLP)</li><li>Data classification &#x26; Governance </li><li>Handling sensitive information type </li><li>M365 encryptions </li><li>Microsoft Message purview encryption </li><li>Protect Information in Microsoft Purview </li><li>Sensitive label management</li><li>Data Loss prevention in MS Purview </li><li>Configure DLP policies for Microsoft Defender for Cloud Apps and Power Platform</li><li>Manage data loss prevention policies and reports in Microsoft 365</li><li>Manage the data lifecycle in Microsoft Purview</li><li>Manage data retention in Microsoft 365 workloads</li><li>Manage records in Microsoft Purview</li></ul></td><td></td><td></td></tr></tbody></table>

## <mark style="color:green;">Service Base Line</mark>

| Network Security    | Asset Management           | End Point Security  |
| ------------------- | -------------------------- | ------------------- |
| Identity Management | Logging & Threat Detection | Backup & Recovery   |
| Privilege Access    | Incident Response          | DevOps Security     |
| Data Protection     | Posture & Vuln Management  | Governance Strategy |

## Quick links

{% embed url="<https://portal.azure.com>" fullWidth="true" %}
Azure Portal
{% endembed %}

Demo


# Manage Azure Resource

In this mini project, let's perform basic Azure Resource Management tasks to get hands-on Azure Administrative features.

### Objective&#x20;

| Exercise                                                                    | Task Name                              |
| --------------------------------------------------------------------------- | -------------------------------------- |
| [<mark style="color:purple;">Task 1</mark> ](/manage-azure-resource/task-1) | Create two RG & deploy Resources to RG |
| [<mark style="color:purple;">Task 2</mark>](/manage-azure-resource/task-2)  | Move Resources b/w RG                  |
| [<mark style="color:purple;">Task 3</mark> ](/manage-azure-resource/task-3) | Deploy Resource locks                  |

Project Architecture&#x20;

<figure><img src="/files/SghIdwS57zx6J1MI9zl9" alt=""><figcaption><p>Architecture Diagram </p></figcaption></figure>


# Task 1

This task we'll create a RG to our nearest location and deploy resources inside it.

{% hint style="info" %}
All resources having same life cycle ideally should belong to same Resource Group
{% endhint %}

1. Visit [Azure Portal](https://portal.azure.com) and Sign-in.
2. Click on Search-box and search for Resource Group and create a new RG
3. Search Resource Group

   <figure><img src="/files/n1fnGxH49Q8vuNTMd8PR" alt=""><figcaption></figcaption></figure>
4. Select Subscription, Give a name to resource group then select nearest zone .Afterwards Review and Create .
5. &#x20;Click on Review and Create&#x20;
6. Search **Disk**, and click on + create&#x20;

<figure><img src="/files/u8HzgbwBt0CA2LAMZGuq" alt=""><figcaption></figcaption></figure>

7. Select your subscription and fill other details.

<figure><img src="/files/XN1OC4rLU85P8X3mLrVC" alt=""><figcaption></figcaption></figure>

8. Change SSD to HDD and reduce Storage Size to avoid extra costing

<figure><img src="/files/7mCcBvWvWyqyaKK2hhqt" alt=""><figcaption></figcaption></figure>

9. From Encryption tab, select Platform-managed Key it means Azure will take care of Keys.

<figure><img src="/files/2Nhe41K3Vp6FxmCdpG9W" alt=""><figcaption></figcaption></figure>

10. &#x20;Enable Public Access only in <mark style="color:red;">**Test**</mark> env

<figure><img src="/files/WFGWGtAsIdf57i4HoVhg" alt=""><figcaption></figcaption></figure>

11. Don't enabled shared Disk option, because we do have to move this resource from 1 resource group to another.

<figure><img src="/files/bCd2eSC7ozqefiXQuPra" alt=""><figcaption></figcaption></figure>

12. &#x20;If you have any Tags, put there or else feel free to keep it blank.

<figure><img src="/files/kFBV9MI2w5tL5kvo1gj1" alt=""><figcaption></figcaption></figure>


# Task 2


# Task 3


# RBAC


# NSG & ASG


# Page 1


# Page 2


# Perimeter Security


# Network Security

<mark style="color:purple;">**LAB 1**</mark>

<details>

<summary>Design and Implement a VNET(Virtual Network )</summary>

Company : Troubleshooter Club LTD&#x20;

Process of migrating infrastructure and applications to Azure . As Network engineer , we need to plan & implement 3 VNET and Subnets

Architecture Diagram&#x20;

<img src="/files/XiJKAwlAXOtj70hyaOgk" alt="" data-size="original">

**Objectives**&#x20;

* Task 1 : Create the troubleshooterclub resource group&#x20;
* Task2: Create the coreServicesVnet virtual network and subnets&#x20;
* Task3: Create the ManufacturingVnet virtual network and subnets&#x20;
* Task4: Create the ResearchVnet virtual network and subnets
* Task5: Verify the creation of the virtual networks and subnets&#x20;

</details>

<details>

<summary>Consideration for Public DNS services</summary>

* Name of Zone must be unique within the RG and Zone must not exist already&#x20;
* Same Zone name can be reused in a different RG or a different Azure Subscription&#x20;
* Where Multiple zones shares the same name, each instance is assigned different name server addresses&#x20;
* Root/Parent domain is registered at the registrar and pointed to Azure NS&#x20;
* Child domains are registered in AzureDNS directly

</details>


# IaaC

Managing Azure with Terraform

<mark style="color:green;">**Definition**</mark>**:** Terraform is an infrastructure as code tool that lets you build, change, and version infrastructure safely and efficiently. This includes low-level components like compute instances, storage, and networking; and high-level components like DNS entries and SaaS features.

<figure><img src="/files/AppV5bZzIQKs2XMYd1rU" alt=""><figcaption><p>Image Source: Terraform Doc</p></figcaption></figure>


# Installation

Please refer official documentation for latest changes and installation

{% embed url="<https://developer.hashicorp.com/terraform/tutorials/azure-get-started/install-cli>" %}

{% hint style="info" %}
Azure Cli should be installed in local system to use Azure resources via API&#x20;
{% endhint %}

{% tabs %}
{% tab title="Debain based Linux Installation " %}

```bash
sudo apt update && sudo apt install -y gnupg software-properties-common
```

{% endtab %}

{% tab title="Second Tab" %}

```
// Some code
```

{% endtab %}
{% endtabs %}

{% code title="Install  HashiCorp GPG key" fullWidth="false" %}

```bash
wget -O- https://apt.releases.hashicorp.com/gpg | \
gpg --dearmor | \
sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg

```

{% endcode %}

{% code title="Verify the key's fingerprint." %}

```bash
gpg --no-default-keyring \
--keyring /usr/share/keyrings/hashicorp-archive-keyring.gpg \
--fingerprint

```

{% endcode %}

{% code title="Add the official HashiCorp repository to your system." %}

```bash
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] \
https://apt.releases.hashicorp.com $(lsb_release -cs) main" | \
sudo tee /etc/apt/sources.list.d/hashicorp.list

```

{% endcode %}

{% code title="Download the package from HashiCorp." %}

```bash
sudo apt update
```

{% endcode %}

{% code title="Install Terraform " %}

```bash
sudo apt install terraform
```

{% endcode %}

{% code title="Verify Installation " %}

```bash
terraform -help
```

{% endcode %}

<figure><img src="/files/EfW9BmanrdzmqulHHQwf" alt=""><figcaption><p>Installation Verification </p></figcaption></figure>

## <mark style="background-color:purple;">VS Code Extension Installation</mark>&#x20;


# Azure  SAST Rules

This contains SAST (static Application Security Testing) rules for shift left approach and maintain code smell and clean coding

RBAC Rules&#x20;

<details>

<summary>Azure custom roles should not grant subscription "Owner" capabilities </summary>

<mark style="color:red;">**Noncompliant code example**</mark>

{% code lineNumbers="true" %}

```json
//Noncompliant code 

resource "azurerm_role_definition" "example" { # Sensitive
  name        = "example"
  scope       = data.azurerm_subscription.primary.id

  permissions {
    actions     = ["*"]
    not_actions = []
  }

  assignable_scopes = [
    data.azurerm_subscription.primary.id
  ]
}


// compliant solution 

resource "azurerm_role_definition" "example" {
  name        = "example"
  scope       = data.azurerm_subscription.primary.id

  permissions {
    actions     = ["Microsoft.Compute/*"]
    not_actions = []
  }

  assignable_scopes = [
    data.azurerm_subscription.primary.id
  ]
}
```

{% endcode %}

</details>

<details>

<summary>Administration services access should be restricted to specific IP addresses.</summary>

#### <mark style="color:red;">What is the potential impact?</mark>

Since Administrative services run with the elevated privileges and thus a vulnerability could have a high impact on the system along with credentials might be leaked through the phishing or similar technique.&#x20;

&#x20;<mark style="color:red;">**Solution**</mark>&#x20;

Restrict access to the remote administrative services to only <mark style="color:purple;">trusted IP</mark> address.\
What should be termed as "Trusted IP "?

Any IP address which is held by system Administrative&#x20;

eg:-&#x20;

```json
// Nonecompliant code example 

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "resources": [
    {
      "name": "networkSecurityGroups/example",
      "type": "Microsoft.Network/networkSecurityGroups/securityRules",
      "apiVersion": "2022-11-01",
      "properties": {
        "protocol": "*",
        "destinationPortRange": "*",
        "sourceAddressPrefix": "*",
        "access": "Allow",
        "direction": "Inbound"
      }
    }
  ]
}

resource securityRules 'Microsoft.Network/networkSecurityGroups/securityRules@2022-11-01' = {
  name: 'securityRules'
  properties: {
    direction: 'Inbound'
    access: 'Allow'
    protocol: '*'
    destinationPortRange: '*'
    sourceAddressPrefix: '*'
  }
}


// compliant solution

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "resources": [
    {
      "name": "networkSecurityGroups/example",
      "type": "Microsoft.Network/networkSecurityGroups/securityRules",
      "apiVersion": "2022-11-01",
      "properties": {
          "protocol": "*",
          "destinationPortRange": "22",
          "sourceAddressPrefix": "10.0.0.0/24",
          "access": "Allow",
          "direction": "Inbound"
      }
    }
  ]
}

resource securityRules 'Microsoft.Network/networkSecurityGroups/securityRules@2022-11-01' = {
  name: 'securityRules'
  properties: {
    direction: 'Inbound'
    access: 'Allow'
    protocol: '*'
    destinationPortRange: '22'
    sourceAddressPrefix: '10.0.0.0/24'
  }
}

```

</details>


# Authentication

This repo contains all  types of security best practices for handling authentication

## 1. How to handle secure password while connecting with the Database ?

Instead of hardcoding passwords, using `env` variable would be much better . Let's take example with Django and python&#x20;

### Problem&#x20;

* Hard code passwords can lead to security vulnerability which is significant security risk&#x20;
* Flexibility issue : can't be modified  password without modifying code or client side&#x20;
* Version control Issue : storing hardcoded password in VS repo, with multiple access can lead to security risk&#x20;

```python
// Non compliant code 


# settings.py

DATABASES = {
    'postgresql_db': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'quickdb',
        'USER': 'sonarsource',
        'PASSWORD': '', # Noncompliant
        'HOST': 'localhost',
        'PORT': '5432'
    }
}


```

```python
// complaint solution


# settings.py
import os

DATABASES = {
    'postgresql_db': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'quickdb',
        'USER': 'sonarsource',
        'PASSWORD': os.getenv('DB_PASSWORD'),
        'HOST': 'localhost',
        'PORT': '5432'
    }
}
```

Let's take another DB example for MySQL  connection&#x20;

```sql
// Non Compliant  code

from mysql.connector import connection

connection.MySQLConnection(host='localhost', user='sonarsource', password='')
```

```sql
// Compliant code

from mysql.connector import connection
import os

db_password = os.getenv('DB_PASSWORD')
connection.MySQLConnection(host='localhost', user='sonarsource', password=db_password)
```

***References***&#x20;

|       |                                                                                |
| ----- | ------------------------------------------------------------------------------ |
| CWE   | <https://cwe.mitre.org/data/definitions/521>                                   |
| OWASP | <https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures/> |


# Docker

This page contains docker SAST rules including Vulnerability, Bug, Code Smell, Security Hotspot

## <mark style="color:purple;">Code Smell</mark>&#x20;

### 1. Descriptive Labels are Mandatory&#x20;

Issue : when one of the mandatory label are missing . Labels help to organise  images by project, record licensing, aid in the automation  and for other reasons.&#x20;

```docker
// Non -compliant solution 


From Ububtu:22.02
RUN my_command
```

```docker
// Compliant Solution 

From Ubuntu:22.02
LABEL maintainer="shubhendu"
LABEL description=" Image is for testing"
LABEL version=1.0
RUN my_command 
```

2. Argument in long RUN instructions should be sorted&#x20;

in Docker file , commands within RUN argument should be sorted alphabetically if order is not enforced by the command.&#x20;

This practice enhance the readability of the code, easier to track modification & prevent potential errors.&#x20;

```docker
// Non-compliant Solution 

FROM ubuntu:20.04

RUN apt-get update && apt-get install -y \
    unzip \
    wget \
    curl \
    git \
    zip
```

```docker
// Non-compliant Solution 

FROM alpine:3.12

RUN apk add unzip wget curl git zip
```

Here commands are not in alphabetically so let's see compliant solution&#x20;

```docker
// Compliant Solution 

FROM ubuntu:20.04

RUN apt-get update && apt-get install -y \
    curl \
    git \
    unzip \
    wget \
    zip
```

```docker
// Compliant Solution 

FROM alpine:3.12

RUN apk add curl git unzip wget zip
```

## <mark style="color:purple;">Security-Hotspot</mark>&#x20;

1. Delivering code in production with debug ft activated is Security-sensitive&#x20;

Why ?&#x20;

Debug instructions or error messages can leak detailed information about the system like application's path or file name&#x20;

Questions to be asked before deploying application to the end users  and if any of the question has "YES" answer then there is a potential Risk&#x20;

{% tabs %}
{% tab title="First Question" %}
The code or configuration enabling the application debug features is deployed on production servers or distributed to end users
{% endtab %}

{% tab title="Second Question" %}
The application runs by default with debug features activated&#x20;
{% endtab %}
{% endtabs %}

```docker
// Non-compliant solution 

FROM example
# Sensitive
ENV APP_DEBUG=true
# Sensitive
ENV ENV=development
CMD /run.sh

```

```docker
// Compliant Solution 

FROM example
ENV APP_DEBUG=false
ENV ENV=production
CMD /run.sh
```

2. Running container as privileged user is security-sensitive&#x20;

\
Running containers as a privileged user weakens their runtime security, allowing any user whose code runs on the container to perform administrative actions.\
In Linux containers, the privileged user is usually named `root`. In Windows containers, the equivalent is `ContainerAdministrator`

<mark style="color:yellow;">`Questions to be Asked`</mark>

{% tabs %}
{% tab title="First Question" %}
Servers services accessible from the Internet&#x20;
{% endtab %}

{% tab title="Second Question" %}
Doesn't require a privileged user to run&#x20;
{% endtab %}
{% endtabs %}

and there is a security risk if any of the Answer is "YES"

<mark style="color:yellow;">**Solution**</mark> :-&#x20;


# Code Like Hacker : Secure Terraform Practices

This contains cloud Native Meetup code snippets

## Admin access should be restricted from the specific IP&#x20;

* ISSUE :  Any Firewall allowing traffic from all IP address to standard n/w port on which admin services traditionally listen such as \
  &#x20;SSH - port#22 : Lead to unauthorised access
* Potential Impact :- \
  &#x20;Privilege Escalation or elevation \
  &#x20;Vulnerability&#x20;

Example&#x20;

#### An ingress rule allowing all inbound SSH traffic for AWS:

```hcl
// Non-compliant code 

resource "aws_security_group" "noncompliant" {
  name        = "allow_ssh_noncompliant"
  description = "allow_ssh_noncompliant"
  vpc_id      = aws_vpc.main.id

  ingress {
    description      = "SSH rule"
    from_port        = 22
    to_port          = 22
    protocol         = "tcp"
    cidr_blocks      = ["0.0.0.0/0"]  # Noncompliant
  }
}
```

#### A security rule allowing all inbound SSH traffic for Azure

```hcl
// Non-compliant code 

resource "azurerm_network_security_rule" "noncompliant" {
  priority                    = 100
  direction                   = "Inbound"
  access                      = "Allow"
  protocol                    = "Tcp"
  source_port_range           = "*"
  destination_port_range      = "22"
  source_address_prefix       = "*"  # Noncompliant
  destination_address_prefix  = "*"
}
```

### Compliant Solution&#x20;

It is recommended to restrict access to remote administration services to only trusted IP addresses. In practice, trusted IP addresses are those held by system administrators or those of [bastion-like](https://aws.amazon.com/quickstart/architecture/linux-bastion/?nc1=h_ls) servers.

#### An ingress rule allowing inbound SSH traffic from specific IP addresses for AWS:

```hcl
// Compliant-code 

resource "aws_security_group" "compliant" {
  name        = "allow_ssh_compliant"
  description = "allow_ssh_compliant"
  vpc_id      = aws_vpc.main.id

  ingress {
    description      = "SSH rule"
    from_port        = 22
    to_port          = 22
    protocol         = "tcp"
    cidr_blocks      = ["1.2.3.0/24"]
  }
}

```

#### A security rule allowing inbound SSH traffic from specific IP addresses for Azure&#x20;

```hcl
// Compliant-code 

resource "azurerm_network_security_rule" "compliant" {
  priority                    = 100
  direction                   = "Inbound"
  access                      = "Allow"
  protocol                    = "Tcp"
  source_port_range           = "*"
  destination_port_range      = "22"
  source_address_prefix       = "1.2.3.0"
  destination_address_prefix  = "*"
}
```

* CWE - [CWE-284 - Improper Access Control](https://cwe.mitre.org/data/definitions/284)


