DOCX

How to use the SAML 2.0 and AD FS implementing API and CLI access control

By Alfred Kennedy,2015-02-07 13:28
49 views 0
How to use the SAML 2.0 and AD FS implementing API and CLI access control

    How to use the SAML 2.0 and AD FS implementing API

    and CLI access control

    AWS support the use of SAML (security assertions markup language) 2.0 joint for identity.Using SAML, you can configure your AWS account and your identity provider (IdP) integration.Once configured, your organization identity provider will be on your joint user authentication and authorization, then joint users can use the single sign-on method to login to the AWS management console.This can not only make your users from remembering another user name and password, and simplifies the administrator's identity management process.Joint users when you want to visit the AWS management console, this method is effective.But when they want to use the AWS CLI or programmatically calls AWS API, will be how?

    In this article, I will show you how to implement joint API and CLI for your users to access.This post provides an example using the AWS Python SDK tools and the integration of some additional client side code.If you have the user needs to this kind of access control, implementation of the program allows you to the management of the user at ease.

    Let's start quickly understand our goal.

    janedoe@Ubuntu64:/tmp$ ./samlapi.py

    Username: AD\janedoe

    Password: ****************

    Please choose the role you would like to assume:

    [ 0 ]: arn:aws:iam::012345678987:role/ADFS-Administrators

    [ 1 ]: arn:aws:iam::012345678987:role/ADFS-Operators

    Selection: 1

    ---------------------------------------------------------------

    Your new access key pair has been stored in the aws configuration

    file /home/janedoe/.aws/credentials under the saml profile.

    Note that it will expire at 2015-05-26T17:16:20Z.

    After this time you may safely rerun this script to refresh your

    access key pair.

    To use this credential call the aws cli with the --profile option

(e.g. aws --profile saml ec2 describe-instances).

    ---------------------------------------------------------------

    Simple API example listing all s3 buckets:

    [, , ,

    , ]

    From the above output, we clearly see?

    1. The system prompt joint user input Active Directory certificate (Active Directory).The certificate used to comparing with configuration of idps for user authentication and authorization.

    2. The system checks the returned SAML assertions, determine the user is authorized to undertake IAM identity and access management role.After the user selects her role expectations, the system use the AWS STS (security token service) to extract the temporary security certificate.

    3. The system automatically to these certificate written to her local AWS certification documents, she can start to make AWS API or CLI call instruction.

    4. Get the sample, sample customized for your organization to the later, you can keep the AWS IAM service provided by control at the same time, use the certificate organization to improve your ability and the degree of automation of AWS API and CLI interface.

    This post will focus on how to use Microsoft active directory (AD FS) joint service.But if you are using other suppliers of similar products, please don't be disappointed because of the basic components should be able to cooperate with other common idps.

    In order to be able to follow this post, you must have:

    An introduction to

    1. Use your organization certificate will AD the FS correctly with your AWS account integration, so that you can access the console.If you need to set up instructions, please refer toEnabling Federation to AWS using Windows Active Directory, ADFS, and SAML 2.0。

    2. Has been in the local workstation installed the new version (2.36 or update) AWS Python SDK tools.

    3. To obtain the minimalAWS certification documents(for example: ~ /.

    Aws/credentials), adjust the content of the files in the following to your preferred area and output format.

    Important: the AWS access key for is not in the structure of the above configuration because the initial AWS STS call by trusted idps validated the returned SAML assertions./ CLI all subsequent API calls are made by the key contained in the AWS STS tokens to validate.Want to get more information, please refer toGiving AWS Console Access to Federated Users Using SAML

    First of all, you need to install the core does not belong to the Python distributions of two modules, specifically, is beautifulsoup4 and requests - NTLM.There are several ways to install the two modules, but the PIP contained in Python version 2.7.9 or update tool, for easy installation of the module.You just need to run the following two commands can be: [default]

    output = json

    region = us-west-2

    aws_access_key_id =

    aws_secret_access_key =

    First of all, run the following command:

    pip install beautifulsoup4

    Then run the following command:

    pip install requests-ntlm

    You should get some similar to the following screenshots output:

    AWS combined process with IdP sponsored login method.In the preparation of the final step, you need to identify a specific is used to trigger the login URL.Starting point is basic IdP cause login URL (the URL is URL you used to joint visit SAML rely on all sides, SAML relied on the parties including the AWS management console).In this case, I use AD 2.0 FS.In this version, the format of the URL for the ofhttps: / / < FQDN > / adfs/ls/IdpInitiatedSignOn. Aspx.If I input the URL into the browser's address bar, I will see a site selection page, as shown in the figure below:

    In order to construct the URL, you need the original idps cause login URL and query string?LoginToRp = urn: amazon: webservices connection.Construct good should be presented in the form of a URL is ofhttps: / / < FQDN > / adfs/ls/IdpInitiatedSignOn. Aspx?LoginToRp = urn: amazon: webservices.Save the URL on the back of the narrative it will be called idpentryurl variables.If you will output the browser's URL address bar in this series, you should still can implement AD FS idps login process.But, you bypass the site selection page, after verification exercise after the URL directly into the AWS management console.If you are interested, you can accessMicrosoft’s websiteTo view the document about the query string.

    Important: be sure to pay close attention to the URL host name in capitals.AD FS in the validation process will use a host name, any mismatch in case will cause validation fails.

    Check the code

    Now that you have to browse the "introduction" part of the steps above, you can start combination control combined with CLI API access integration code.I will explain in detail the process so that you can follow my rhythm.First, let's do some basic import and variable Settings.

#!/usr/bin/python

    import sys

    import boto.sts

    import boto.s3

import requests

    import getpass

    import ConfigParser

    import base64

    import xml.etree.ElementTree as ET

    from bs4 import BeautifulSoup

    from os.path import expanduser

    from urlparse import urlparse, urlunparse

    from requests_ntlm import HttpNtlmAuth

    ########################################################################## # Variables

    # region: The default AWS region that this script will connect # to for all API calls

    region = 'us-west-2'

    # output format: The AWS CLI output format that will be configured in the # saml profile (affects subsequent CLI calls)

    outputformat = 'json'

    # awsconfigfile: The file where this script will store the temp # credentials under the saml profile

    awsconfigfile = '/.aws/credentials'

    # SSL certificate verification: Whether or not strict certificate # verification is done, False should only be used for dev/test sslverification = True

    # idpentryurl: The initial URL that starts the authentication process.

idpentryurl =

    'https:///adfs/ls/IdpInitiatedSignOn.aspx?loginToRp=urn:amazon:webservices'

    ##########################################################################

    Adjust variables in the code for your specific area (such as the us - west - 2, us - east - 1, etc.) and formatting preferences (such as json, text, or table), and then inserted into the upper part of this post is variable idpentryurl value.

    Build up basic environment, prompt the user to retrieve the user's certificate from the standard input.At the back of this post I will discuss how we support other forms of certificate.

    # Get the federated credentials from the user

    print "Username:",

    username = raw_input()

    password = getpass.getpass()

    print ''

    Located in the first line print statements "Username" behind the comma may look like a bug, it is actually a Python in order to prevent the first line print statements to add line breaks and use tip.You will also notice that getpass () the use of this method, this method is to prevent password are displayed in the output.

    Next, we use Python request module combination authentication information, formulization send IdP HTTPS requests, as the fragment shown below.Hypothesis testing is successful, the AD FS returns the response message contains SAML assertions. # Initiate session handler session = requests.Session() # Programatically

     get the SAML assertion # Set up the NTLM authentication handler by using

     the provided credential session.auth = HttpNtlmAuth(username, password,

     session) # Opens the initial AD FS URL and follows all of the HTTP302 redirects

     response = session.get(idpentryurl, verify=sslverification) # Debug the

     response if needed #print (response.text)

    So far, the IdP response have got safely.So, let's cover and abandoned our original variables used to store user name and password, because we no longer need them.As a higher

    level of language, the Python does not like C language can provide direct memory operations to cover these variables.But the characteristics of the Python can ensure that the certificate is not wandering everywhere (authenticated).

    # Overwrite and delete the credential variables, just for safety username

     = '##############################################' password = '##############################################'

     del username del password

    As I mentioned earlier, we need the SAML assertions can be found in the response message of IdP.The following code USES BeautifulSoup module to extract SAML assertions. # Decode the response and extract the SAML assertion soup =

    BeautifulSoup(response.text.decode('utf8'))

     assertion = '' # Look for the SAMLResponse attribute of the input tag (determined

     by # analyzing the debug print lines above) for inputtag in soup.find_all('input'):

     if(inputtag.get('name') == 'SAMLResponse'):

    #print(inputtag.get('value'))

     assertion = inputtag.get('value')

    This video just iterate through all of the HTML input tags until it finds the name is SAMLResponse label.We are looking for Base64 encoded assertions contained in the label attribute values.Before going further, we need to further processing SAML authentication response message, to extract the user authorized to the role of the list.The list is stored in the SAML attribute namedhttps://aws.amazon.com/SAML/Attributes/Role, as shown in the following code.

    # Parse the returned assertion and extract the authorized roles awsroles

     = [] root = ET.fromstring(base64.b64decode(assertion)) for saml2attribute

     in

    root.iter('{urn:oasis:names:tc:SAML:2.0:assertion}Attribute'): if

    (saml2attribute.get('Name')

     == 'https://aws.amazon.com/SAML/Attributes/Role'): for saml2attributevalue

     in

    saml2attribute.iter('{urn:oasis:names:tc:SAML:2.0:assertion}AttributeValue'):

     awsroles.append(saml2attributevalue.text) # Note the format of the attribute

     value should be role_arn,principal_arn # but lots of blogs list it as principal_arn,role_arn

     so let's reverse # them if needed for awsrole in awsroles: chunks = awsrole.split(',')

     if'saml-provider' in chunks[0]: newawsrole = chunks[1] + ',' + chunks[0]

     index = awsroles.index(awsrole) awsroles.insert(index, newawsrole) awsroles.remove(awsrole)

    In the first part of above, I use Pythonxml etree. ElementTree parsing module SAML assertions.Despite assertions look not very neatly, but explicit namespace and name that we find relatively easy.

    In the second ring, the code is doing some active error prevention, to ensure that contained in the role of ARN resource name (amazon) sorting is correct. Now we know the role that the user is authorized.Next, the code asks the user roles they want to use.

    # If I have more than one role, ask the user which one they want,

    # otherwise just proceed

    print ""

    if len(awsroles) > 1:

     i = 0

     print "Please choose the role you would like to assume:"

     for awsrole in awsroles:

     print '[', i, ']: ', awsrole.split(',')[0]

     i += 1

     print "Selection: ",

     selectedroleindex = raw_input()

     # Basic sanity check of input

     if int(selectedroleindex) > (len(awsroles) - 1):

     print 'You selected an invalid role index, please try again'

     sys.exit(0)

     role_arn = awsroles[int(selectedroleindex)].split(',')[0]

     principal_arn = awsroles[int(selectedroleindex)].split(',')[1]

    else:

     role_arn = awsroles[0].split(',')[0]

     principal_arn = awsroles[0].split(',')[1]

    If the user as long as a character, the character will automatically be used.Otherwise, the system will prompt the user from a simple enumeration list they want to use the role.

    Now, it becomes very simple.Because we have retrieved the SAML assertions, extract the various ARN.We only need to call the standard AWS STS services to request the AWS temporary security certificate.This really is the key to the whole process.We have made every effort until now for the following simple AssumeRolewithSAML API calls for various parameters.

    # Use the assertion to get an AWS STS token using Assume Role with SAML

     conn = boto.sts.connect_to_region(region) token =

    conn.assume_role_with_saml(role_arn,

     principal_arn, assertion)

    Important note: SAML assertions from the configured trusted idps, its role is to the API calls as authentication certificate.

    Now we have get a certificate from the AWS STS, the next step is to insert the certificates AWS certification documents of a particular file, as shown in the fragments below.Through this step, you will be able to use the temporary security certificate or the CLI for any number of times of API calls, until the certificate has expired. # Write the AWS STS token into the AWS credential file home = expanduser("~")

     filename = home + awsconfigfile # Read in the existing config file config

Report this document

For any questions or suggestions please email
cust-service@docsford.com