Archive for June, 2018

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

 

 

 

Advertisements

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

Azure Application gateway

Posted: June 18, 2018 in Azure

Azure Application Gateway is a web traffic load balancer that enables  manage traffic to web applications using.Application Gateway is a layer 7 load balancer, which means it works with web traffic only (HTTP/HTTPS/WebSocket)

In Azure portal click new-Application gateway

 

1.PNG

For application gateway dedicated subnet is created (10.0.3.0/24)

 

2.PNG

Create availability set

 

3.PNG

and create public address

4.PNG

Creating Backend Pool

Backend pools can be composed of NICs, virtual machine scale sets, public IPs, internal IPs, fully qualified domain names (FQDN), and multi-tenant back-ends like Azure Web Apps. Application Gateway backend pool members are not tied to an availability set.

In resource group click on Application gateway-Backend Pools.Default pool is created-click on it

 

5.PNG

On target drop-down list select Virtual machine

 

6.png

Select Virtual machines (in this case there are 2 VM’s:app1 and app2

7.PNG

Health probes

Azure Application Gateway by default monitors the health of all resources in its back-end pool and automatically removes any resource considered unhealthy from the pool. Application Gateway continues to monitor the unhealthy instances and adds them back to the healthy back-end pool once they become available and respond to health probes.

Click on Health probes (default one is created alongside with Application gateway)

 

8.PNG

For host type 127.0.0.1, for path type /index.txt

On app1 and app2 servers,IIS is installed and under c:\intetpub\wwwroot folder index.txt file is created.It will be used as “probe” to check backed server availability (HTTP response 200)

Content of index.txt

This is server 1-on app1 machine

This is server 2-on app2 machine

9.PNG

Interval:Configures the probe interval checks in seconds.

Timeout:Defines the probe time-out for an HTTP response check.

UnhealthyThreshold:The number of failed HTTP responses needed to flag the back-end instance as unhealthy.

 

HTTP settings

Click on default HTTP settings

 

10.PNG

Select health probe and port

 

11.PNG

When a user request is received, Application Gateway applies the configured rules to the request and routes it to a back-end pool instance. It waits for a configurable interval of time for a response from the back-end instance. By default, this interval is 30 seconds. If Application Gateway does not receive a response from back-end application in this interval, user request would see a 502 error.

In Application Gateway settings,in Overview properties we can see public IP

 

12.png

 

13.PNG

 

Azure Log Analytics

Posted: June 16, 2018 in Azure

Log Analytics is part of Microsoft Azure’s overall monitoring solution. Log Analytics monitors cloud and on-premises environments to maintain availability and performance.

In Azure portal, click new resource-Activity Log Analytics

 

1.PNG

Click Create New OMS workspace.Operations Management Suite (OMS) is a collection of cloud-based services for managing on-premises and cloud environments.All data collected by Activiry Log Analytics is stored in the OMS repository, which is hosted in Azure.

 

2.PNG

 

 

3.PNG

After resource is created, click on Solution we just created

 

4.png

Adding Azure Virtual Machine to OMS

Under Workspace data sources click Virtual Machines

 

5.PNG

Click connect-it will take few minutes to connect VM to OMS

 

6

From overview property click OMS portal

 

9.png

Click settings

 

10.png

Click Data-Windows Event Logs-add events which you want to monitor by OMS (in this case Application and System)

 

11.PNG

 

From OMS properties click Log Search

 

 

 

7.png

Click All collected data

 

13.PNG

After 15-20 minutes “Event” type should appear and log types we specified will appear in OMS

 

14.PNG

This script performs following:

Untitled.png

import boto3
import collections
import datetime
import time
import sys 
ses = boto3.client('ses')
AWSAccountID=boto3.client('sts').get_caller_identity()['Account']
AWSUser=boto3.client('sts').get_caller_identity()['UserId']
ec = boto3.client('ec2', 'eu-west-1')
ec2 = boto3.resource('ec2', 'eu-west-1')
from datetime import datetime
from dateutil.relativedelta import relativedelta

#create date variables 

date_after_month = datetime.now()+ relativedelta(days=7)
#date_after_month.strftime('%d/%m/%Y')
today=datetime.now().strftime('%d/%m/%Y')

def send_mail(email_from, email_to, subject, body):
    smtp_address = 'smtp.office365.com'
    provider_username = 'sender@company.com'
    provider_password = 'Pass'
    smtpserver = smtplib.SMTP(smtp_address, 587)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo() # extra characters to permit edit
    smtpserver.login(provider_username, provider_password)
    header = 'To: ' + email_to + '\n' + 'From: ' + email_from + '\n' + 'Subject: ' + subject + '\n'
    msg = header + '\n ' + body + ' \n\n'
    smtpserver.sendmail(provider_username, email_to, msg)
    smtpserver.quit()
def lambda_handler(event, context):
  #Get instances with Owner Taggs and values Unknown/known
    instance_ids = []
    reservations = ec.describe_instances().get('Reservations', []) 

    for reservation in reservations:
     for instance in reservation['Instances']:
        tags = {}
        for tag in instance['Tags']:
            tags[tag['Key']] = tag['Value']
            if tag['Key'] == 'Name':
              name=tag['Value']
        if not 'Owner' in tags or tags['Owner']=='unknown' or tags['Owner']=='Unknown':
              instance_ids.append(instance['InstanceId'])  

                #Check if "TerminateOn" tag exists:

              if 'TerminateOn' in tags:
                  #compare TerminteOn value with current date
                    if tags["TerminateOn"]==today:

                    #Check if termination protection is enabled
                     terminate_protection=ec.describe_instance_attribute(InstanceId =instance['InstanceId'] ,Attribute = 'disableApiTermination')
                     protection_value=(terminate_protection['DisableApiTermination']['Value'])
                     #if enabled disable it
                     if protection_value == True:
                        ec.modify_instance_attribute(InstanceId=instance['InstanceId'],Attribute="disableApiTermination",Value= "False" )
                    #terminate instance
                     ec.terminate_instances(InstanceIds=instance_ids)
                     body="AWS Account:" + AWSUser + "\n\nAWS Account Number:" + AWSAccountID + "\n\nInstance Name:" + name + "\n\nInstance ID:" + instance['InstanceId'] + "\n\nTo be Removed In:Now\n\n\n\rNote:\n\nOwner tag is missing from this instance, hence,instance is removed." 
                     send email that instance is terminated
                     send_mail('sender@example.com', 'recipient@example.com', 'Ireland:Notification of terminating instances', body)

                    else:
                      

                      now=datetime.now()
                      future=tags["TerminateOn"]
                      TerminateOn = datetime.strptime(future, "%d/%m/%Y")
                      days= (TerminateOn-now).days
                      body="AWS Account:" + AWSUser + "\n\nAWS Account Number:" + AWSAccountID + "\n\nInstance Name:" + name + "\n\nInstance ID:" + instance['InstanceId'] + "\n\nTo be Removed In:Now\n\n\n\rNote:\n\nOwner tag is missing from this instance, hence,instance is removed."
                      send_mail('sender@example.com', 'recipient@example.com', 'Ireland:Notification of terminating instances', body) 

              else:
                 if not 'TerminateOn' in tags:#, create it
                  ec2.create_tags(Resources=instance_ids,Tags=[{'Key':'TerminateOn','Value':date_after_month.strftime('%d/%m/%Y')}])
                  ec.stop_instances(InstanceIds=instance_ids)
                  body="AWS Account:" + AWSUser + "\n\nAWS Account Number:" + AWSAccountID + "\n\nInstance Name:" + name + "\n\nInstance ID:" + instance['InstanceId'] + "\n\nTo be Removed In:Seven Days\n\n\n\rNote:\n\nOwner tag is missing from this instance.\nIf you do not wish this instance to be removed, please update the Owner tag." 
                  send_mail('sender@example.com', 'recipient@example.com', 'Ireland:Notification of shutting down instances', body)