Archive for the ‘Amazon Web Services (AWS)’ Category

Fortinet Fortigate is Firewall appliance, available as Virtual Machine in Azure and Amazon.In this example we’ll be deploying Fortigate to Amazon.

In Launch Instance click AWS Marketplace and choose product

 

3.PNG

and instance type

4

Select VPC, if you try adding two Interfaces, you’ll get “We can no longer assign a public IP to your instance”, so assign only one network interface

5.PNG

I have VPC with 2 subnets:192.168.10.0/24 and 192.168.20.0/24. i assigned interface 192.168.10.0 which will be “external”.

I created secondary interface and assigned it to 192.168.20.0 subnet.This one will be internal.

Creating second interface

In EC2 menu click Network Interfaces-Create Network Interface

 

6.PNG

 

Select subnet and Security group

7.PNG

 

Attaching interface

Click on your Fortigate instance-Actions-Networking-Attach Network Interface

 

8.png

 

9

After instance is started, we can connect to it.Use internal address, not a public one, otherwise, when changing interface role, you’ll lose connection to Fortigate.

Default username is admin, password is instance ID

Click Network-interfaces-right-click interface-Edit

11.PNG

Set alias, and change role

13.PNG

 

14.PNG

Advertisements

lThis script performs following:

Untitled.png


import boto3
import collections
import datetime
import time
import sys 

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 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 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)
                     print "terminated" + str(instance_ids)
                     #send email that instance is terminated

                    else:
                    #Send an email to engineering that this instance will be removed X amount of days (calculate the date based on today's date and the termination date."

                      now=datetime.now()
                      future=tags["TerminateOn"]
                      TerminateOn = datetime.strptime(future, "%d/%m/%Y")
                      days= (TerminateOn-now).days
                      print str(instance_ids) +  " will be removed in "+ str(days) + " days"

              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)

                  print "was shut down "+format(','.join(instance_ids))

In previous post we configured EC2 instance for System Manager Service and executed command manually against EC2 instance.That’s nice, but we can schedule command execution using Lambda.In this example we’ll schedule powershell command which will check if instance is in idle mode (no RDP connection) and, if yes, instance will be stopped.

In that way we’ll save some money 🙂

First, install System Manager agent on your Windows instance, create IAM System Manager role and assign that role to your instances.Refer to my previous post for more info.

Then add 2 tags:Auto_Stop_Enabled-True and Instance_Used_As_Desktop (so we can filter instances this command will be run against)

2

You can skip these tags creations but also don’t remember to remove is references from Powershell script.

Creating Lambda Function

From AWS console click on Services-Lambda (or just type Lambda in search bar)

2

Click Create function:

2

Enter a name for function-from Role drop-down menu choose create custom role and click Create function

2.PNG

Type a name and click Edit

2

Delete current JSON code and put this one instead:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"ec2:DescribeInstances",
"ec2:DescribeTags",
"ec2:DescribeInstanceAttribute",
"ec2:DescribeInstanceStatus"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "logs:CreateLogGroup",
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"ssm:DescribeDocument",
"ssm:DescribeDocumentParameters",
"ssm:GetDocument",
"ssm:GetParameter"
],
"Resource": [
"arn:aws:ssm:*:*:document/*",
"arn:aws:ssm:*:*:parameter/*"
]
},
{
"Effect": "Allow",
"Action": [
"ssm:ListInventoryEntries",
"ssm:ListDocumentVersions",
"ssm:ListDocuments",
"ssm:SendCommand"
],
"Resource": "*"
}
]
}

After clicking Apply you’ll be redirected back to Create function-Click Create function

2.PNG

Now scroll down until Function code section-right click auto_stop-New folder-name it modules.

2.PNG

Now right click on modules folder-new-folder-give it name controls

2.PNG

Now, under controls folder create a file named index.js

2

Put following code into index.js Hibernation is Log name,AutoStopScript source name, If you don’t want EC2 tags, then remove

{
Name: "tag:Instance_Used_As",
Values: ["Desktop"]
},
{
Name: "tag:Auto_Stop_Enabled",
Values: ["True","true", "Yes", "yes"]
}
]

auto_stop/modules/control/index.js code:

// Import Dependencies
let AWS = require(‘aws-sdk’);

module.exports.getInstanceIds = () => {
return new Promise(
(resolve, reject) => {
let ec2 = new AWS.EC2();
let params = {
Filters: [
{ Name: “instance-state-name”,
Values: [“running”]
},
{
Name: “tag:Instance_Used_As”,
Values: [“Desktop”]
},
{
Name: “tag:Auto_Stop_Enabled”,
Values: [“True”,”true”, “Yes”, “yes”]
}
]
};

ec2.describeInstances(params, (err, data) => {
if (err) reject(err);

let instanceIds = [];
let reservations = “”;

try {
reservations = data.Reservations;
}
catch(err) {
reject(err);
}
if(Array.isArray(reservations)) {
reservations.forEach((reservation) => {
reservation.Instances.forEach((instance) =>{
instanceIds.push(instance.InstanceId);
});
});
if(instanceIds.length >= 1) {
resolve(
{
“InstanceIds”: instanceIds
}
);
}
else {
reject(new Error(“[Error] getInstanceIds: No instances found.”));
}
}
else {
reject(new Error(“[Error] getInstanceIds: Reservations is not an array.”));
}
});
}
);
};

module.exports.hibernateInstances = (controlObj) => {
return new Promise(
(resolve, reject) => {
let ec2 = new AWS.EC2();
let ssm = new AWS.SSM();

let instanceIds = controlObj.InstanceIds;

let params = {
InstanceIds: instanceIds
};

let ssmParams = {
InstanceIds: instanceIds,
DocumentName: “AWS-RunPowerShellScript”,
Parameters: {
“workingDirectory”:[“”],
“executionTimeout”:[“1200”],
“commands”:[
“########################”,
“#### VARIABLES #########”,
“########################”,
“$eventLogName = \”Hibernation\””,
“$eventSourceName = \”AutoStopScript\””,
“$eventLogIds = @{“,
” 1001 = \”Event log initialised.\”;”,
” 1002 = \”No active RDP sessions were found. Proceed to hibernate the instance.\”;”,
” 1003 = \”Active RDP session detected. Abort the hibernation attempt.\”;”,
” 1004 = \”Hibernation is enabled. Preparing for shutdown.\”;”,
” 3001 = \”CPU Usage is higher than the threshold. The hibernation is cancelled.\””,
” 4001 = \”Trouble accessing ‘qwinsta’ executable. Make sure ‘qwinsta’ is in the PATH.\”;”,
” 4002 = \”Trouble accessing ‘powercfg’. Make sure it is in PATH.\”;”,
” 4003 = \”Hibernation was not enabled successfully. Check C:\\ for enough drive space.\”;”,
” 4004 = \”Hibernation attempt failed. Please check if ‘shutdown’ is in PATH.\”;”,
“”,”}”,””,
“$mailMessages = @{“,
” hibernationEnableError = \”Error: Failed to enable hibernation.\”;”,
” hibernationStartError = \”Error: Failed to hibernate an instance.\”;”,”}”,”$minAverageCPU = 20 #If an instance has less than 20% average CPU usage in the period of 5 minutes, it will get shut down.”,””,”########################”,”#### INITIALIZATION ####”,”########################”,
“#### EVENT LOG INIT”,”Try {“,” $null = Get-EventLog -LogName $eventLogName -ErrorAction Stop”,”}”,”Catch {“,” Try {“,” New-EventLog -LogName $eventLogName -Source $eventSourceName -ErrorAction Stop”,” } “,” Catch {“,” #Noop”,” }”,” “,” Write-EventLog -LogName $eventLogName -Source $eventSourceName -EntryType Information -EventId 1001 -Category 1 -Message $eventLogIds.1001″,”}”,””,
“########################”,”#### FUNCTIONS #########”,”########################”,”# # Used to send notifications to the uses.”,”# Function Send-RESTMailMessage {“,”# Param (“,”# $Subject,”,”# $Message,”,”# $Recipient”,”# )”,”# $_headers = New-Object \”System.Collections.Generic.Dictionary[[String],[String]]\””,”# $_headers.Add(\”Content-Type\”, ‘application/json’)”,”# $_headers.Add(\”Cache-Control\”, ‘no-cache’)”,
“# $_headers.Add(\”x-api-key\”, ‘flREiNZkVK2lgGHWHUmxr1VPP8GIfLTz7uVH6eKz’)”,””,”# $body = @{“,”# subject=$Subject”,”# message=$Message”,”# auth_key=’sDfFXAk421412DSAkxKLaksdKASdFG'”,”# recipients=@($Recipient)”,”# }”,””,”# $body = $body | ConvertTo-JSON”,””,”# $response = Invoke-RestMethod -Uri \”https://ekiss3x6gl.execute-api.us-east-1.amazonaws.com/v1/notifications/system\” -Method Post -Headers $headers -Body $body”,”# return $response”,”# }”,
“”,”Function Get-ActiveRDPSessions {“,” # Check for any active RDP sessions.”,” # This function relies on \”qwinsta\” tool which comes bundled with Windows.p”,” # The function returns \”true\” if there are active RDP sessions or \”false\” if there aren’t any.”,” Param (“,” $EventLogName,”,” $EventSourceName,”,” $EventIds”,” )”,” Try {“,” $_allSessions = qwinsta”,” }”,” Catch {“,” Write-EventLog -LogName $EventLogName -Source $EventSourceName -EntryType Error -EventId 4001 -Category 4 -Message $EventIds.4001″,” return 1″,” }”,” “,” ForEach($_s in $_allSessions) {“,” If($_s -match \”rdp\” -and $_s -match \”Active\”) {“,” Write-EventLog -LogName $EventLogName -Source $eventSourceName -EntryType Information -EventId 1003 -Category 1 -Message $EventIds.1003″,” return \”ActiveSessionFound\””,” }”,” }”,” “,” Write-EventLog -LogName $EventLogName -Source $eventSourceName -EntryType Information -EventId 1002 -Category 1 -Message $EventIds.1002″,” return \”NoActiveSessionFound\””,”}”,””,”Function Enable-Hibernation {“,” Param (“,” $EventLogName,”,” $EventSourceName,”,” $EventIds”,” )”,””,” Try {“,” $_process = Start-Process powercfg -ArgumentList \”/h\”, \”on\” -PassThru -ErrorAction Stop”,” Start-Sleep -Seconds 3″,” }”,” Catch {“,” Write-EventLog -LogName $EventLogName -Source $EventSourceName -EntryType Error -EventId 4002 -Category 4 -Message $EventIds.4002″,” return 1″,” }”,””,” If ($_process.ExitCode -eq 0) {“,” Write-EventLog -LogName $EventLogName -Source $EventSourceName -EntryType Information -EventId 1004 -Category 1 -Message $EventIds.1004″,” return \”Enabled\””,””,” } “,” Else {“,” Write-EventLog -LogName $EventLogName -Source $EventSourceName -EntryType Error -EventId 4003 -Category 4 -Message $EventIds.4003″,” return 1″,” }”,”}”,””,”Function Start-Hibernation {“,” Param (“,” $EventLogName,”,” $EventSourceName,”,” $EventIds”,” )”,””,” Try {“,” $_process = Start-Process shutdown -ArgumentList \”/h\” -PassThru -ErrorAction Stop”,” }”,” Catch {“,” Write-EventLog -LogName $EventLogName -Source $EventSourceName -EntryType Error -EventId 4004 -Category 4 -Message $EventIds.4004″,” return 1″,” }”,”}”,””,”Function Check-CPUUsage {“,” $_samples = 5″,” $_intervalSeconds = 60″,” $_cpuLoadAverage = 0″,” For($i = 0; $i -ne $_samples; $i++) {“,” $_cpuLoadAverage += (Get-WmiObject win32_processor).LoadPercentage”,” Start-Sleep -Seconds $_intervalSeconds”,” }”,””,” return $_cpuLoadAverage / $_samples “,”}”,””,””,”########################”,”#### MAIN ##############”,”########################”,”$rdpSessionStatus = Get-ActiveRDPSessions -EventLogName $eventLogName -EventSourceName $eventSourceName -EventIds $eventLogIds”,””,”If ($rdpSessionStatus -eq \”NoActiveSessionFound\”) {“,” #Enable Hibernation”,” Enable-Hibernation -EventLogName $eventLogName -EventSourceName $eventSourceName -EventIds $eventLogIds”,” “,” If(Check-CPUUsage -lt $minAverageCPU) {“,””,””,” # TODO Notify User”,” # TODO Wait 10 minutes”,” # TODO Check for active RDP sessions again”,””,” #Hibernate”,” Start-Hibernation -EventLogName $eventLogName -EventSourceName $eventSourceName -EventIds $eventLogIds”,” }”,” Else {“,” Write-EventLog -LogName $EventLogName -Source $EventSourceName -EntryType Warning -EventId 3001 -Category 3 -Message $EventIds.3001″,” return 0″,” }”,”} “,”Else {“,” return 0″,”}”
]
},
MaxErrors: “0”,
TimeoutSeconds: 120
}

// Hibernate instances
ssm.sendCommand(ssmParams, function(err, data) {
if (err) reject(err);
resolve(data);
});
resolve(instanceIds);
console.log(instanceIds);
}
);
};

 

Now click on “parent” index.js (under auto_stop only)

 

2.PNG

paste following code (change AWS zone to fit your needs):

 

// Global Module Imports
let AWS = require(‘aws-sdk’);
AWS.config.region = “eu-west-1”;
let controls = require(“./modules/controls”);

// This is the function AWS Lambda will execute.
exports.handler = (event, context, callback) => {

// Execute the power control
controls.getInstanceIds()
.then(controls.hibernateInstances)
.catch((err) => {
callback(err);
});
};

At the end it should be like this:

 

2.PNG

 

Now, we need to schedule our function:

in Add trigger section click CloudWatch Events

 

2.PNG

Give it name and set schedule

 

You can use the following sample cron strings when creating a rule with schedule.

Minutes Hours Day of month Month Day of week Year Meaning
0 10 * * ? * Run at 10:00 am (UTC) every day
15 12 * * ? * Run at 12:15 pm (UTC) every day
0 18 ? * MON-FRI * Run at 6:00 pm (UTC) every Monday through Friday
0 8 1 * ? * Run at 8:00 am (UTC) every 1st day of the month
0/15 * * * ? * Run every 15 minutes
0/10 * ? * MON-FRI * Run every 10 minutes Monday through Friday
0/5 8-17 ? * MON-FRI * Run every 5 minutes Monday through Friday between 8:00 am and 5:55 pm (UTC)

 

In this example i set it to run every 20 minutes.

 

2.PNG

 

It should be something like this:

 

2

When you click on run_auto_stop_script you’ll get following picture:

 

2

 

If your instance is idle, it should be stopped. You can check it from AWS console-EC2-SYSTEM-MANAGER SHARED RESOURCES-Run Command

3.PNG

 

AWS Systems Manager is a management service that helps automatically collect software inventory, apply OS patches, create system images, and configure Windows and Linux operating systems (running scripts).

Creating System Manager role

In AWS console click on IAM

6

Roles-create role, choose EC2 and click next

Untitled.png

Then select EC2 Role for Simple Systems Manager and click Next

Untitled.png

in Attached permission policy select AmazonEC2RoleforSSM

Untitled

Click next, give role a name and click Create role

Assigning role to EC2 instance

In this example i used Windows Server 2016 EC2 instance.Select EC2 in list of services, select instance-Action-Instance Setting-Attach/Replace IAM Role

Untitled

Select System Manager Role and click Apply

Untitled

Installing  SSM agent

Login to EC2 instance,download and install SSM agent.Start service:

Start-Service AmazonSSMAgent

 

Running command

In AWS console-EC2 service-Scroll until SYSTEM MANAGER SHARED RESOURCES-Managed instances

 

Untitled.png

 

Select instance and click Run a command

Untitled.png

 

Select one of the commands

Untitled

 

Type command and click Run

Untitled.png

Click on Command ID

 

Untitled.png

 

Then click output-View Output

Untitled

 

Untitled.png

 

 

In order to change subnet of EC2 instance stop it firs

 

1.png

 

Then create AMI image from that instance

 

2.png

 

 

3.PNG

Click on new AMI then launch it

 

4.png

 

Select desired subnet

 

5.png

 

 

6.PNG

 

New instance is in different subnet and data are preserved

 

7.PNG

In previous article we created federation trust between Azure and AWS by creating Amazon user and used it’s credentials to create trust between Azure and AWS (automatic provisioning).This method has 2 main drawbacks: it takes a long time for Azure to retrive all IAM roles,and it’s not possible to provide more than 1 IAM credentials (situation when need to federate same Azure Enterprise application with 2 or more AWS accounts).Most of the steps are same as for manual provisioning but i’ll put it here again for the sake of transparency

Adding Amazon Application to Azure portal

On Azure portal Azure Active Directory-Enterprise Applications-All applications-New Application

1

In search box type Amazone-select Amazon Web Services (AWS)

2

On AWS app properties click on Single sign-on

3

Click Add attribute

4

Add attributes as in picture below

Attribute name Attribute value Namespace
RoleSessionName user.userprincipalname https://aws.amazon.com/SAML/Attributes
Role user.assignedroles https://aws.amazon.com/SAML/Attributes

 

 

5

In the SAML Signing Certificate section, select Metadata XML. Then save the metadata file on your computer.

5-1

5-2

Then click Save

5-3

AWS Console:Creating Provider and IAM role

In AWS console we need to add Provider, IAM role and policy

Select Identity and access management-IAM

6

Identity Providers-Create Provider

7

Choose SAML as Provider Type,set name and browse for metadata file downloaded from Azure portal

9

10

Still in IAM Click Roles-Create Role

11

Select Saml 2.0 Federation-SAML provider-provider we created earlier-Allow programatic and AWS Management Console Access (Attribute and Value fields populate automatically)

12

In Attach permission policies click Next:Review

13

In Create Role create as many roles as you need

14

Besides Azure_Role, i created another one and attached one IAM policy, we’ll map this role to another Azure AD Group

Untitled

Azure portal:Create User and Group-add user to group

In this section we’ll map Azure AD group to AWS role we just created (Azure_Role)

Creating new user:

Azure Active Directory-Users-All Users:

26

Create user

27

Creating AD group

Azure Active Directory-Groups

Untitled

Specify Group Type,name-Membership Type:Assigned-specify user(s) to add to group-Select-Create

Untitled

In the same way i created another Azure AD group (AWS_Second_Test_Group) to map it with another IAM role we created earlier (AWS_Second_Test_Role), i added Don.Hall user to this group too

Editing Azure Active directory manifest file

Manifest file is a JSON file that represents application’s identity configuration.We’ll edit this file to map Azure AD group with AWS IAM Role.Access scopes and roles are exposed through this file

In Azure portal, in search box type App Registrations-Select Amazon Web Services (AWS)

Untitled.png

Click on Manifest

Untitled

Now, we’ll map IAM AWS roles to Azure AD groups:

IAM Role name Azure AD Group Name
 Azure_Role Azure_AD_Group
AWS_Second_Test_Role AWS_Second_Test_Group

Ideally, names of IAM Roles and groups should be the same to avoid confusion

In order to edit manifest file we need to obtanin IAM Role ARN,AWS Identity provider ARN and Azure AD group ID (Azure AD Group ID must be unique-as a rule of thumb i just changed last 2 digits)

Capture

AWS IAM role ARN:

Untitled.png

Untitled.png

AWS Identity provider ARN:

Untitled

Azure Group’s ID:

Click on group-Properties:

Capture

Untitled

Remember, Azure AD group ID’s needs to be unique, so change last digit(s) values

These 2 sections are added to manifest file:

displayName:Name of Azure AD group

id:id of Azure AD group (changes last 2 digits-needs to be unique)

value:AWS IAM role ARN,AWS identity provider ARN

"appRoles": [
    {
      "allowedMemberTypes": [
        "User"
      ],
      "displayName": "AWS_Second_Test_Group",
      "id": "faa9acbc-49db-4a04-9a66-2050998f1c15",
      "isEnabled": true,
      "description": "Azure AD Second group",
      "value": "arn:aws:iam::233135199200:role/AWS_Second_Test_Role,arn:aws:iam::233135199200:saml-provider/WindowsAD"
    },
    {
      "allowedMemberTypes": [
        "User"
      ],
      "displayName": "Azure_AD_Group",
      "id": "b40569c7-ebf0-4c32-959c-b0b3b1cbfc12",
      "isEnabled": true,
      "description": "Azure AD First group",
      "value": "arn:aws:iam::233135199200:role/Azure_Role,arn:aws:iam::233135199200:saml-provider/WindowsAD"
    },

If we need to map more roles to groups we just need to add allowedMemberTypes sections (separate each one with comma)

Here is complete manifest file:

{
  "appId": "1def2fa6-5467-4565-b3f0-e598b3007b42",
  "appRoles": [
    {
      "allowedMemberTypes": [
        "User"
      ],
      "displayName": "AWS_Second_Test_Group",
      "id": "faa9acbc-49db-4a04-9a66-2050998f1c15",
      "isEnabled": true,
      "description": "Azure AD Second group",
      "value": "arn:aws:iam::233135199200:role/AWS_Second_Test_Role,arn:aws:iam::233135199200:saml-provider/WindowsAD"
    },
    {
      "allowedMemberTypes": [
        "User"
      ],
      "displayName": "Azure_AD_Group",
      "id": "b40569c7-ebf0-4c32-959c-b0b3b1cbfc12",
      "isEnabled": true,
      "description": "Azure AD First group",
      "value": "arn:aws:iam::233135199200:role/Azure_Role,arn:aws:iam::233135199200:saml-provider/WindowsAD"
    },
    {
      "allowedMemberTypes": [
        "User"
      ],
      "displayName": "msiam_access",
      "id": "7dfd756e-8c27-4472-b2b7-38c17fc5de5e",
      "isEnabled": true,
      "description": "msiam_access",
      "value": null
    }
  ],
  "availableToOtherTenants": false,
  "displayName": "Amazon Web Services (AWS)",
  "errorUrl": null,
  "groupMembershipClaims": null,
  "optionalClaims": null,
  "acceptMappedClaims": null,
  "homepage": "https://signin.aws.amazon.com/saml?metadata=aws|ISV9.1|primary|z",
  "informationalUrls": {
    "privacy": null,
    "termsOfService": null
  },
  "identifierUris": [
    "http://awsDC46DF5ECB354EEA858E81622348A0BE",
    "http://instanceid_8b1025e4-1dd2-430b-a150-2ef79cd700f5_EAAEA402D2364790A14A5099A13A3B7E",
    "http://aws/d38c1eb9-ca01-420f-a982-210c0583dc49"
  ],
  "keyCredentials": [],
  "knownClientApplications": [],
  "logoutUrl": null,
  "oauth2AllowImplicitFlow": false,
  "oauth2AllowUrlPathMatching": false,
  "oauth2Permissions": [
    {
      "adminConsentDescription": "Allow the application to access Amazon Web Services (AWS) on behalf of the signed-in user.",
      "adminConsentDisplayName": "Access Amazon Web Services (AWS)",
      "id": "e81ccfaa-9095-4cbc-87fe-10538a57f314",
      "isEnabled": true,
      "type": "User",
      "userConsentDescription": "Allow the application to access Amazon Web Services (AWS) on your behalf.",
      "userConsentDisplayName": "Access Amazon Web Services (AWS)",
      "value": "user_impersonation"
    }
  ],
  "oauth2RequirePostResponse": false,
  "objectId": "dd1dc07d-87dc-48bb-9fd3-1c0274c789a5",
  "parentalControlSettings": {
    "countriesBlockedForMinors": [],
    "legalAgeGroupRule": "Allow"
  },
  "passwordCredentials": [],
  "publicClient": false,
  "replyUrls": [
    "https://signin.aws.amazon.com/saml"
  ],
  "requiredResourceAccess": [],
  "samlMetadataUrl": null
}

Azure Active Directory-Enterprise Applications-Amazon Web Services (AWS)-Users and Groups-Add User

Capture.PNG

In Users section Assign user- in Roles section new roles should appear-select role

Capture

And assign it

Capture

Capture

Make sure manual provision method is selected (Amazon Web Services (AWS)-Provisioning

Capture

Testing access to AWS console

Don.Hall should be able now to acces to Amazon Web Console

Go to http://myapps.microsoft.com, log in as Don.Hall

click on Amazon Web Service, you should be able to sign in automatically to AWS console

31

 

Capture

In this article we’ll create Azure AD User and log him in into Amazon Web Console using single sign-on

Adding Amazon Application to Azure portal

Azure Active Directory-Enterprise Applications-All applications-New Application

1

In search box type Amazone-select Amazon Web Services (AWS)

2

On AWS app properties click on Single sign-on

3

Click Add attribute

4

Add attributes as in picture below

Attribute name Attribute value Namespace
RoleSessionName user.userprincipalname https://aws.amazon.com/SAML/Attributes
Role user.assignedroles https://aws.amazon.com/SAML/Attributes

 

5.png

In the SAML Signing Certificate section, select Metadata XML. Then save the metadata file on your computer.

5-1

5-2

Then click Save

5-3

Configuring AWS part

In AWS console we need to add Provider, IAM role and policy

Select Identity and access management-IAM

6

Identity Providers-Create Provider

7.png

Choose SAML as Provider Type,set name and browse for metadata file downloaded from Azure portal

9

10

Still in IAM Click Roles-Create Role

11

Select Saml 2.0 Federation-SAML provider-provider we created earlier-Allow programatic and AWS Management Console Access (Attribute and Value fields populate automatically)

12

In Attach permission policies click Next:Review

13

In Create Role create as many roles as you need

14

Creating Policy

Policies-Create policy (this policy will grab all IAM roles from AWS account)

15

Click JSON tab and paste following code:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iam:ListRoles"
],
"Resource": "*"
}
]
}

 

 

16

17

Creating new AWS user

We need to create new user,attach policy we just created,get credentials so we can submit it to Azure AWS application so we can get all Amazon AWS roles

18

19

20

Download CSV file (Access and shared access keys are there)

21

In Azure portal,in AWS app properties click Provisioning-for client secret enter AWS user access key,for Sercret token enter AWS user secret and click Test Connection

22

Scroll down, set On for Provision status then click Save

23

Creating Azure AD  user

Azure Active Directory-Users-Al Users

26

Create user

27

Enabling Azure Single sign-on for user

In AWS application properties select Users and Groups

28

Select user and click Select button

29

Click assign

30

Testing access to AWS console

Don.Hall should be able now to acces to Amazon Web Console

Go to http://myapps.microsoft.com, log in as Don.Hall

click on Amazon Web Service, you should be able to sign in automatically to AWS console

 

31

 

32