Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts

Tuesday, May 24, 2016

Azure Resource Lock: Safeguard Your Critical Resources

Prevention is better than Cure – There were quite a few instances when I thought I should have applied this logic. This has even more significance if you are playing around public cloud more so while dealing with mission critical resources there. There must have been numerous occasions when you would have to protect you resources from some unwarranted human actions, to put it bluntly we are seeking a solution prevent other users in organization from accidentally deleting or modifying critical resources.

Azure has given us couple of ways to apply that level of control, firstly with role-based access control (RBAC), With the Reader and various Contributor roles RBAC is a great way to help protect resources in Azure. You can effectively limit the actions that a user can take against a resource. However, even with one of the Contributor roles, it is still possible to delete specific resources. This makes it very easy to accidently delete an item. 


Azure Lock provides you the options using which you can effetely control any such adventure. Unlike RBACK, you use management locks to apply a restriction across all users and roles. To learn about setting permissions for users and roles, see Azure Role-based Access Control. Using Resource lock you can lock a particular subscription, a particular resource group or even a specific resource. With this in place authorize users can still be able to read or modify the resources but they CAN NOT breach that lock and delete the same.


To make this happen you have to apply the Resource Lock Level to aforementioned scopes. You can set the lock level to CanNotDelete or ReadOnly(As of now these two are the only options supported). CanNotDelete means authorized users can still read and modify a resource, but they can't delete it. ReadOnly means authorized users can only read from a resource, but they can't modify or delete it.

When you apply a lock at a parent scope, all child resources inherit the same lock.

One point worth mentioning here is that you will also need to be in either an Owner or User Access Administrator role for the desired scope, because to play with Resource Lock it’s prerequisite to have access to Microsoft.Authorization/* or Microsoft.Authorization/locks/* actions(only these two have appropriate permissions).

Create Resource Lock Using ARM Template


With Azure Resource Manager template we can lock the resources at the time of its creation. An ARM template is a JSON-formatted template file which provide a declarative way to define the deployment of Azure resources. 

Here is the example of how to create a lock on particular Storage Account-

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "lockedResource": {
      "type": "string"
    }
  },
  "resources": [
    {
      "name": "[concat(parameters('lockedResource'), '/Microsoft.Authorization/utLock')]",
      "type": "Microsoft.Storage/storageAccounts/providers/locks",
      "apiVersion": "2015-01-01",
      "properties": {
        "level": "CannotDelete"
      }
    }
  ]
}

If you see the example clearly the name of storage account coming via parameter while the most important section to be noticed is how the lock (utLock) has been created by concatenating the resource name with /Microsoft.Authorization/ and the name of the lock.

Create Resource Lock using PowerShell

Placing a resource lock on an entire group could be helpful in situations where you want to ensure no resources in that group are deleted. With below example I have tried to create a resource lock on a particular resource Group” UT-RG”

New-AzureResourceLock -LockLevel CanNotDelete `
 -LockNotes 'No deleting!' `
 -LockName 'utLock' `
 -ResourceGroup 'UT-RG' -Verbose

To remove the resource Lock make use of Remove-AzureResourceLock cmdlet, make sure you are providing proper ResourceId.
> Remove-AzureResourceLock -ResourceId '/subscriptions/xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/UT-RG/providers/Microsoft.Storage/storageAccounts/utsrt/providers/Microsoft.Authorization/locks/utLock'
#Deleting Resource Group 
Remove-AzureresourceGroup -Name 'UT-RG' -Force -Verbose

Off late Azure has brought this support to ARM Portal as well, to achieve the similar things via portal click the Settings blade for the resource, resource group, or subscription that you wish to lock, select Locks.Once prompted Give the lock a name and lock level and you are immune to those talked about unwanted situations.It gives you options to lock an entire subscription to ReadOnly if malicious activity was detected.

Wednesday, August 19, 2015

Powershell: Automating AWS Route 53 Record Sets

Speaking of Cloud Environment where auto - scaling, self-healing servers have replaced the more conservative way of scaling – We can’t have classic manual way of DNS management.  I.e. Each new instance launched by auto scaling group should assign itself a human-readable hostname. In these cases Instance itself should be equipped enough to add its corresponding entry under Route 53. We can make use of Route53 and PowerShell to impalement this automation from Windows machine.

What Is Route 53?

Route 53 is a complete DNS solution provided by Amazon that lets you control every aspect of the name resolution process for your domain. You choose a registrar to reserve your domain, as common practice they often be managing all the DNSs for your domain. But if you are looking for more granular control over this Route 53 is one of the services you should be interested in. A details description of Route 53 is beyond the scope of this article, but you can check at AWS Route 53

Automation Script

I have wrapped the whole script into a function.We have used PowerShell V3 , consider that as prerequisite.Having Amazon cmdlets loaded should be done before expecting it to work.Pointers related to it's functioning :
  • Execution of this script will only materialize given working pair of Secret Key & Access Key
  • It validates the Record type with values mentioned under ValidateSet
  • If wait is specified, the function will wait until AWS confirms that the change is in sync. To be more specific it verifies whether entry has been propagated under specified Zone. By default i have kept it as false
  • If you have mentioned wait as true, waitinterval specifies the interval in milliseconds between each polling
  • Every parameter can be overridden why calling this function
Function Create-AwsRoute53Record
{
    [CmdletBinding(SupportsShouldProcess=$true)]
    Param (
                [String]$AccessKeyID="****************",
        [String]$SecretAccessKeyID="*****************",
                [String]$Region="us-east-1",
                [Parameter(Mandatory=$true)] $Zone,
               [ValidateSet("A", "SOA", "PTR", "MX", "CNAME","TXT","SRV","SPF","AAAA","NS")]
                [String]$RecordType,
               [Parameter(Mandatory=$true)]
                [String]$Name,
              [Parameter(Mandatory=$true)]$Value,
               $TTL,
               $wait = $false,
              [int]$waitinterval = 1000

        )
   
    Process
    {
     Set-AWSCredentials -AccessKey $InfoObject.AccessKey  -SecretKey $InfoObject.SecretKey
    Set-DefaultAWSRegion -Region $region
    $zoneEntry = (Get-R53HostedZones) | ? {$_.Name -eq "$($Zone)."}
 
$hostedZone = $zoneEntry.Id
        if (@($zoneEntry).count -eq 1) {
                $Record = new-object Amazon.Route53.Model.ResourceRecord
                $record.Value = $Value
                 #add the trailing dot
        if (!($Name.EndsWith(".")) -and $Name)
            {$Name += "."}

        $ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
        $ResourceRecordSet.Type = $RecordType
        $ResourceRecordSet.ResourceRecords = $Record
        $ResourceRecordSet.Name = $Name
        $ResourceRecordSet.TTL = $TTL


        $change = New-Object Amazon.Route53.Model.Change
        $change.Action = "Create"
        $change.ResourceRecordSet = $ResourceRecordSet
     
        $Changes = (New-Object -TypeName System.Collections.ArrayList($null))
        $Changes.Add($Change)

        Try
        {
            $result = Edit-R53ResourceRecordSet -ChangeBatch_Changes $Changes -HostedZoneId $hostedZone
         
        }
        Catch [system.Exception]
        {
            Write-error $error[0]
        }
     
        if ($result)
        {
            if ($wait)
            {
            #Keep polling the result until it is no longer pending
            Do
                {
                    #get change status
                    if ($SecondPoll)
                        {Start-Sleep -Milliseconds $waitinterval}
                   $status=Get-R53Change -Id $result.Id
                    $SecondPoll = $true
                    Write-verbose "Waiting for changes to sync. Current status is $($status.Status.Value)"
                }
            Until ($status.Status.Value -eq "INSYNC")

     
            }
     
            $Status
        }
     }
  }
}

Script Execution

Below we have a sample execution which captures the Public IP of AWS instance ,  and subsequently add it to specified Zone as A Name record Type.

# Change the values as per your specification i.e Zone , Name , RecordType and TTL. Wait is enabled to provide added control.
$LocalIP = Invoke-RestMethod -Uri http://169.254.169.254/latest/meta-data/local-ipv4 -Method Get
$LocalIP=$LocalIP.Trim()
Create-AwsRoute53Record -Zone xyz.com -RecordType A -Name testing.xyz.com  -Value $LocalIP -TTL 500  -wait $true

Wednesday, August 5, 2015

Powershell: Automating AWS Security Groups

To provision and manage EC2-Instances in AWS cloud that comply with industry standards and regulations, Individuals administrating that should understand the security mechanisms within AWS framework—both those that are automatic and those that require configuration.Let’s take a look at Security Group which falls under the latter category.

As there is no "Absolute Security Group" which can be plugged in to satisfy the universal need, we should always be open for its modification.Automating so via Powershell will provide predictable/consistent results.

What Is Security Group?

Every VM created through AWS Management Console (or via scripts) can have association with one or multiple Security Groups (in case of VPC it can be up to 5). By default all the inbound and out bound traffic flow at instance level is blocked from elsewhere. We should automate the infrastructure to open only the ports satisfying the customer need. This implies that we should add rules to each Security Group for ingress/ egress as per customer requirement.For more details have a look at AWS Security Group

It is duly important to allow traffic only from valid source IP addresses; this will substantially prune security attack surface, use of 0.0.0.0/0 as IP range makes things vulnerable for sniffing or tampering of infrastructure. Traffic between VMs should always traverses through Security Groups, we can achieve this by allowing initiators Security Group- ID as source. 

Automation Script

I have kept this as a single block ,if one wishes they can create a function out of it. few things worth considering :
  • Execution of this script will only materialize given working pair of Secret Key & Access Key
  • This script make use of filtering functionality, whereby it expect end user to provide some Name-Pattern ,selection of Security Group is driven by aforementioned pattern
  • To facilitate the whole operation you have to provide certain parameters i.e.[IpProtocol , FromPort , ToPort , Source]
  • Source parameter can be interpreted in two ways, you can either provide IpRanges in CIDR block format or choose another Security Group as source in the from of UserIdGroupPair
<#
    .SYNOPSIS
    Simple script to safely assign/revoke Ingress Rules from VPC Security Group .
    
    .DESCRIPTION
    Script first checks to see what are the rules has beein specified for update,if already assigned will do no harm. 
    If assginement is successful, same can be verified at AWS console.
    
    NOTE:  Script must be updated to include proper pattern, security credentials.
#>

# Update the following lines, as needed:

Param(
          [string]$AccessKeyID="**********",
          [string]$SecretAccessKeyID="********",
          [string]$Region="us-east-1",
          [string]$GrpNamePattern="*vpc-sg-pup_winC*",
          [string]$GroupId="sg-xxxxxxxx",
          [string]$CidrIp="0.0.0.0/0",
          [switch]$SetAws=$true,
          [switch]$Revoke,
          [switch]$Rdp=$true,
          [switch]$MsSql=$true
         )

     $InfoObject = New-Object PSObject -Property @{
        AccessKey = $AccessKeyID
        SecretKey = $SecretAccessKeyID
        Region=$Region
        GrpNamePattern = $GrpNamePattern
        GroupId=$GroupId
        CidrIp=$CidrIp
}
if($SetAws)
    {
 Set-AWSCredentials -AccessKey $InfoObject.AccessKey  -SecretKey $InfoObject.SecretKey 
 Set-DefaultAWSRegion -Region $region
    }
       $PublicGroup = New-Object Amazon.EC2.Model.UserIdGroupPair
       $PublicGroup.GroupId= $InfoObject.GroupId

       $filter_platform = New-Object Amazon.EC2.Model.Filter -Property @{Name = "group-name"; Values = $InfoObject.GrpNamePattern}
       $SG_Details=Get-EC2SecurityGroup -Filter $filter_platform |SELECT GroupId, GroupName

       $rdpPermission = New-Object Amazon.EC2.Model.IpPermission -Property @{IpProtocol="tcp";FromPort=3389;ToPort=3389;UserIdGroupPair=$PublicGroup}

       $mssqlPermission = New-Object Amazon.EC2.Model.IpPermission -Property @{IpProtocol="tcp";FromPort=1433;ToPort=1433;IpRanges=$InfoObject.CidrIp}
       $permissionSet = New-Object System.Collections.ArrayList

     if($Rdp){ [void]$permissionSet.Add($rdpPermission) }

if($MsSql){ [void]$permissionSet.Add($mssqlPermission) }

   if($permissionSet.Count -gt 0)
  {
   try{
if(!$Revoke){
      "Granting to $($SG_Details.GroupName)"
       Grant-EC2SecurityGroupIngress -GroupId $SG_Details.GroupId -IpPermissions $permissionSet 
 }
  else{
  "Revoking to $($SG_Details.GroupName)"
  Revoke-EC2SecurityGroupIngress -GroupId $SG_Details.GroupId -IpPermissions $permissionSet
}
    }
catch{
if($Revoke){
Write-Warning "Could not revoke permission to $($SG_Details.GroupName)"
}
          else{
Write-Warning "Could not grant permission to $($SG_Details.GroupName)"
   }
    }
}


what we are looking at being able to automate Creation/updation of Security Group.Use this script in case you ran into frequent changing of Security Groups.

P.S. This script has been written keeping VPC  in mind, Different parameter usage between VPC and EC2 security groups should be take care of.