Archive for the ‘Azure’ Category

Create user in Azure AD and give him read rights over subscription and Site recovery contributor role over Azure Recovery Vault

1.PNG

Encrypt password file and install Azure module:

$username = "user@example.com"
$pwdTxt = Get-Content "C:\ExportedPassword.txt"
$securePwd = $pwdTxt | ConvertTo-SecureString
$cred = new-object -typename System.Management.Automation.PSCredential `
-argumentlist $username, $securePwd
Login-AzureRmAccount -Credential $cred | out-null
$vault = Get-AzureRmRecoveryServicesVault -Name "Vault"
$VaultFileLocation = Get-AzureRmRecoveryServicesVaultSettingsFile -SiteRecovery -Vault $vault
Import-AzureRmRecoveryServicesAsrVaultSettingsFile -Path $VaultFileLocation.FilePath
$Fabrics = Get-AzureRmRecoveryServicesAsrFabric
$Containers = Get-AzureRmRecoveryServicesAsrProtectionContainer -Fabric $Fabrics
$items = Get-AzureRmRecoveryServicesAsrReplicationProtectedItem -ProtectionContainer $Containers
$filename = "C:\trapper.imports";
write-host $filename;
foreach ($item in $items)
{
'"{0}" {1}' -f "server",'replication['+$item.RecoveryAzureVMName+']',""""+$item.ReplicationHealth+"""" | Add-Content -LiteralPath $filename -Encoding "Default" -Force;
}
cd "C:\Program Files\Zabbix Agent\bin\win64"
.\zabbix_sender.exe -z zabbix_server -p 10051 -c "C:\Program Files\Zabbix Agent\conf\zabbix_agentd.win.conf" -i $filename -vv
rm -Path $VaultFileLocation.FilePath
rm -Path $filename

 

Create zabbix item:

Name/key:replication[VM01]
Type:trapper

Type of infomation:Text

 

Create Trigger:
{server:replication[VM1].str(“Critical”)}=1 or {server:replication[VM01].nodata(180m)}=1

Schedule it by Task Scheduler:

Program/Script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

Add argument: (Optional): “C:\azure_replication.ps1”

Strart in (Optional): C:\

Advertisements

I used this powershell script as starting point.

Install powershell in Zabbix server.

Copy azure_rss.ps1 to /opt/zabbix/azure_rss (make that folder if it doesn’t exists,give zabbix user ownership)

 

azure_rss.ps1:

 

CLS
$a= $hsg.Content
[xml]$ret = $hsg.Content.TrimStart("")
#$ret.rss.channel.item | Select-Object *
#write-host ""
if($ret.rss.channel.item.category -eq $null){
        #write-host $ret.rss.channel.title
        #write-host $ret.rss.channel.title " On : "  $ret.rss.channel.pubDate
        write-output "All services are working properly" > /tmp/out.txt
       }
Else
    {
    $c = $ret.rss.channel.title + " On : " + $ret.rss.channel.pubDate"Issue Category : " + $ret.rss.channel.item.category + $ret.rss.channel.title + " On : " + $ret.rss.channel.pubDate + " Details : " + $ret.rss.channel.item.title + $ret.rss.channel.item.description
    write-output $c > /tmp/out.txt
    #write-host $ret.rss.channel.title " On : "  $ret.rss.channel.pubDate
    #Write-Host "Issue Category : " $ret.rss.channel.item.category
    #write-host ""
    #write-host ""
}
rv hsg, ret

 

I had to redirect output to text file because some hex symbols in output.

copy trap.sh to /opt/zabbix/azure_rss (“azure” is zabbix host)

trap.sh:

#!/bin/bash
pwsh /opt/zabbix/azure_rss/azure_rss.ps1
var=$(cat "/tmp/out.txt")
zabbix_sender -z localhost -p 10051 -s "azure" -k status.azure -o "$var"

Create cron job to run script on interval you predefined

 

 

On Zabbix server, create item:

name:status.azure

Type:Zabbix trapper

key:status.azure

Type of information:Text

 

Create Trigger:

Expression: {hostname:status.azure.str(“Issue Category”)}=1

Because full string output will be lengthy , full error message won’t be visible so we must click-Monitoring-latest data-specify host to see full script output.

Monitoring Azure resources with Zabbix

Posted: August 21, 2018 in Azure

I used this post as starting point.

Creating Azure application

(ID/keys will be used for authentication to Azure)

In Azure portal click Azure Active directory-App registrations-new App registration

1.png

2.PNG

In App registrations select All apps from drop-down menu-click on Zabbix application

3.png

Write down application ID (we’ll use it on scripts)

4.png

Click Settings-Keys-set a name,duration and click Save

5.png

Write down key

6.PNG

Write down TenantID

7.png

Write down Subscription ID-from Azure dashboard,click Cost Management + Billing under my subscription write subscription ID

8.png

Give application read rights to resource group

click on resource group-Access control (IAM)

Untitled.png

click Add-select Reader role-Assign access to Azure AD user,group or application and select Zabbix application

2

Install powershell on Zabbix server (CentOS)

# Register the Microsoft RedHat repository
curl https://packages.microsoft.com/config/rhel/7/prod.repo | sudo tee /etc/yum.repos.d/microsoft.repo
# Install PowerShell
sudo yum install -y powershell

Copy all files in azure.zip to /usr/lib/zabbix/externalscripts, make sure *.sh files are executable

Supported services are SQL,storage account,Virtual Machines and Virtual Network gateway

All available services and metric: https://docs.microsoft.com/en-us/azure/monitoring-and-diagnostics/monitoring-supported-metrics

Time periods (monitoring intervals) are called timegrains

time_grains = {
"PT1M" => "1 Minute",
"PT5M" => "5 Minutes",
"PT1H" => "1 Hour",
"PT12H" => "12 Hours"
}

In trapper.ps1 and azure.ps1 substitute TenantID,applicationID, application key in appropriate sections/

Files can be downloaded from here

Testing

For VM:

./azure.sh resource group subscription vm

For SQL:

./azure.sh resource group subscription sql

For network gateway:

./azure.sh resource group subscription vng

For Storage account

./azure.sh resource group subscription storage

[root@ip-172-31-27-77 externalscripts]# ./azure.sh RG  subscriptionD storage
{"data":[
{
"{#ID}": "/subscriptions/111-222-333/resourceGroups/RG/providers/Microsoft.Storage/storageAccounts/storageaccount",
"{#STORAGEACCOUNT}": "storageaccount"
},
{
"{#ID}": "/subscriptions/111-222-333/resourceGroups/RG/providers/Microsoft.Storage/storageAccounts/storageaccount",
"{#STORAGEACCOUNT}": "storageaccount"
},
{
"{#ID}": "/subscriptions/111-222-333/resourceGroups/RG/providers/Microsoft.Storage/storageAccounts/storageaccount",
"{#STORAGEACCOUNT}": "storageaccount"
}
]
}

give ownership of azure.json to zabbix user:

chown zabbix:zabbix azure.json

create dummy host and attach template, specify resource group and subscription ID

9.PNG

Test zabbix trapper:

./trapper.sh zabbix-dummy-host

if no issues,create cron job for trapper (for example to run it every 15 minutes):

*/15 * * * * /usr/lib/zabbix/externalscripts/trapper.sh dummy-host

On Amazon side:

Create new elastic IP

Select Virtual Private Cloud-Elastic IPs-Allocate new address

1.PNG

Click allocate

2.PNG

I used default VPC if you need to create new VPC,take a look here

Create EC2 instance and assign VPC (default or custom one and subnet)

8.png

Allocate Elastic IP to instance-in EC2 select instance-Actions-Associate address

9.png

Resource Type-instance-select instance and  Private IP

10.PNG

Azure portal

Create Virtual Network Gateway (details here)

Create Local Network Gateway

3.png

IP Address:Amazon Elastic IP (created earlier)

Address Space (Amazon VPC subnet to which EC2 instance is assigned)

4.png

5.PNG

Once Local network gateway is created go to Connections-Add

6.PNG

Select Virtual Network gateway,local network gateway and shared key

7.PNG

Copy Virtual network gateway IP

11

find out Azure VM network

Click on Azure VM-Networking to find out subnet name

12.png

write down subnet, it will be needed for Powershell script

13.png

On AWS EC2 instance install RRAS and configure IPSec VPN.In this case 137.117.170.80 is Azure Virtual Network Gateway IP,10.0.1.0/24 Azure VM subnet and 123456 Secret Key

# Windows Azure Virtual Network

# This configuration template applies to Microsoft RRAS running on Windows Server 2012 R2.
# It configures an IPSec VPN tunnel connecting your on-premise VPN device with the Azure gateway.

# !!! Please notice that we have the following restrictions in our support for RRAS:
# !!! 1. Only IKEv2 is currently supported
# !!! 2. Only route-based VPN configuration is supported.
# !!! 3. Admin priveleges are required in order to run this script

Function Invoke-WindowsApi(
[string] $dllName,
[Type] $returnType,
[string] $methodName,
[Type[]] $parameterTypes,
[Object[]] $parameters
)
{
## Begin to build the dynamic assembly
$domain = [AppDomain]::CurrentDomain
$name = New-Object Reflection.AssemblyName 'PInvokeAssembly'
$assembly = $domain.DefineDynamicAssembly($name, 'Run')
$module = $assembly.DefineDynamicModule('PInvokeModule')
$type = $module.DefineType('PInvokeType', "Public,BeforeFieldInit")

$inputParameters = @()

for($counter = 1; $counter -le $parameterTypes.Length; $counter++)
{
$inputParameters += $parameters[$counter - 1]
}

$method = $type.DefineMethod($methodName, 'Public,HideBySig,Static,PinvokeImpl',$returnType, $parameterTypes)

## Apply the P/Invoke constructor
$ctor = [Runtime.InteropServices.DllImportAttribute].GetConstructor([string])
$attr = New-Object Reflection.Emit.CustomAttributeBuilder $ctor, $dllName
$method.SetCustomAttribute($attr)

## Create the temporary type, and invoke the method.
$realType = $type.CreateType()

$ret = $realType.InvokeMember($methodName, 'Public,Static,InvokeMethod', $null, $null, $inputParameters)

return $ret
}

Function Set-PrivateProfileString(
$file,
$category,
$key,
$value)
{
## Prepare the parameter types and parameter values for the Invoke-WindowsApi script
$parameterTypes = [string], [string], [string], [string]
$parameters = [string] $category, [string] $key, [string] $value, [string] $file

## Invoke the API
[void] (Invoke-WindowsApi "kernel32.dll" ([UInt32]) "WritePrivateProfileString" $parameterTypes $parameters)
}

# Install RRAS role
Import-Module ServerManager
Install-WindowsFeature RemoteAccess -IncludeManagementTools
Add-WindowsFeature -name Routing -IncludeManagementTools

# !!! NOTE: A reboot of the machine might be required here after which the script can be executed again.

# Install S2S VPN
Import-Module RemoteAccess
if ((Get-RemoteAccess).VpnS2SStatus -ne "Installed")
{
Install-RemoteAccess -VpnType VpnS2S
}

# Add and configure S2S VPN interface
Add-VpnS2SInterface -Protocol IKEv2 -AuthenticationMethod PSKOnly -NumberOfTries 3 -ResponderAuthenticationMethod PSKOnly -Name 137.117.170.80 -Destination 137.117.170.80 -IPv4Subnet @("10.0.1.0/24:100") -SharedSecret 123456

Set-VpnServerIPsecConfiguration -EncryptionType MaximumEncryption

Set-VpnS2Sinterface -Name 137.117.170.80 -InitiateConfigPayload $false -Force

# Set S2S VPN connection to be persistent by editing the router.pbk file (required admin priveleges)
Set-PrivateProfileString $env:windir\System32\ras\router.pbk "137.117.170.80 " "IdleDisconnectSeconds" "0"
Set-PrivateProfileString $env:windir\System32\ras\router.pbk "137.117.170.80 " "RedialOnLinkFailure" "1"

# Restart the RRAS service
Restart-Service RemoteAccess

# Dial-in to Azure gateway
Connect-VpnS2SInterface -Name 137.117.170.80

Test connection

get-VpnS2Sinterface

14.PNG

Connection from EC2 to Azure

 

15.PNG

 

 

 

In this example we’ll connect virtual networks located in different Azure regions.This connections is called VNet to VNet.VNet-to-VNet connectivity utilizes the Azure virtual gateways to connect two or more virtual networks together.

0.PNG

 

Creating Gateway subnet-West Europe

Before deploying Virtual Network Gateway we need first to deploy gateway subnet

In subnet properties click + Gateway subnet

1.png

2

Creating Virtual network gateway

In Azure portal click new resource-Virtual network gateaway

 

3.png

Gateway type:VPN

VPN Type:route-based

 

4.PNG

 

Creating virtual network in North Europe

 

5.PNG

Creating Gateway subnet

 

6.png

Defining subnet

7.PNG

Creating Virtual Gateway

8.png

 

9.PNG

In similar way Virtual Network gateway is created in west europe (gateway subnet-10.0.2.0/24)

 

Creating virtual machine in North Europe region

VM is created in North Europe and assigned to vnet-northeurope network

 

0.PNG

Creating VM in West Europe

similar for Virtual machine in West Europe

0.PNG

Creating VNet peering

in NorthEurope Virtual network gateway click Connections-Add

 

11.PNG

 

Specify shared key and opposite network gateway-Virtual network gateway from west-europe (as second gateway)

 

12.PNG

 

Create VNet peering from opposite side-from west europe virtual gateway click-connections-add connection-for second virtual gateway specify north europe virtual gateway-same shared key

 

13.PNG

On both sides, on Virtual network gateway-under connections,connection state should be connected

 

14.PNG

 

14.PNG

Connection from north europe VM to VM in west europe using private IP and vice-versa

 

 

15.PNG

Web application firewall (WAF) is a feature of Application Gateway that provides centralized protection of  web applications from common exploits and vulnerabilities.

Web Application Firewall work differently from a standard IP firewall. A normal firewall is designed to block individual TCP or UDP ports, or to restrict the type of traffic that’s allowed to flow across a particular port. However, WAFs are designed to monitor HTTP or HTTPS traffic that’s being sent to a Web application. The firewall’s job is to determine whether the traffic is normal user traffic, or if it’s something malicious. An example of a malicious request might be a hidden field manipulation attack. If malicious traffic is detected, then the WAF will block the request to prevent it from reaching the Web application server, and will typically also terminate the session.

In Azure portal click new resource-Application Gateway

1.PNG

Select WAF (SKU size needs to be minimum medium)

2.PNG

Choose network and subnet

Firewall modes:

Detection-malicious access will be allowed and logged

Prevention:malicious access will be denied

3.PNG

Creating Backend pool

On Application gateway properties click Backend Pools-add your web servers to pool

4.PNG

Test access:

6.png

7.PNG

Simulating atack

http://40.115.6.212/?XSSAttack=%22%3E%3Cscript%3Einserting-bad-script-here%3C/script%3E%3C%22

Access will be denied

 

8.PNG

We can allow specific traffic based on OWASP 3.O rule set, in example below ATTACK-XSS and ATTACK-SQLI will be allowed (script above)

On Web application firewall click on Advanced rule configuration

 

9.PNG

 

In previous post we deployed Application gateway.In this one we’ll host multiple sites on 2 test VM’s: app1 and app2

 

1.PNG

 

We need first to map Application gateway’s public IP to our  DNS (GoDaddy in my case)

 

12

 

I’ll simulate publishing of 2 sites.My domain is astrahome.xyz

so i created 2 host (A) records:

images.astrahome.xyz

text.astrahome.xyz

 

2

Then i simulated images site on app1 machine

3.PNG

 

and text site on app2

4

 

Creating Backed pool for image site

On application gateway properties click on Backed Pools-Add

Under targets specify Virtual machine and add app1

5.PNG

 

Creating backed pool for textiles site

Same as for above, just name is different

 

6.PNG

 

Creating listeners

 

On Application gateway properties click on Listeners-Multi-site

 

7.png

For text site

 

9.PNG

 

For imagesite

 

8.PNG

 

Creating Rules

On Application gateway properties click rules-Basic

 

9-1.png

 

 

9-2.PNG

 

 

9-3

We should be able now to reach text.astrahome.xyz

 

10.PNG

and images.astrahome.xyz

11.PNG