Esempio n. 1
0
def assume_role(role_arn, mfa_token_name=None, duration_minutes=60):
    if mfa_token_name:
        token = mfa_read_token(mfa_token_name)
        code = mfa_generate_code(mfa_token_name)
        response = sts().assume_role(RoleArn=role_arn,
                                     RoleSessionName="n-sess-" +
                                     id_generator(),
                                     SerialNumber=token['token_arn'],
                                     TokenCode=code,
                                     DurationSeconds=(duration_minutes * 60))
    else:
        response = sts().assume_role(RoleArn=role_arn,
                                     RoleSessionName="n-sess-" +
                                     id_generator(),
                                     DurationSeconds=(duration_minutes * 60))
    return response['Credentials']
Esempio n. 2
0
def resolve_account():
    global ACCOUNT_ID
    if not ACCOUNT_ID:
        try:
            ACCOUNT_ID = sts().get_caller_identity()["Account"]
        except BaseException:
            pass
    return ACCOUNT_ID
Esempio n. 3
0
def assumed_role_name():
    global ROLE_NAME
    if not ROLE_NAME:
        try:
            roleArn = sts().get_caller_identity()['Arn']
            if ":assumed-role/" in roleArn:
                ROLE_NAME = roleArn.split("/")[1]
        except BaseException:
            pass
    return ROLE_NAME
Esempio n. 4
0
def adfs_aws_login():
    conf = init()
    username = None
    # Get the federated credentials from the user
    if not conf.NO_PROMPT:
        sys.stdout.write("Username [" + conf.DEFAULT_USERNAME + "]: ")
        username = input()
    if not username:
        if conf.DEFAULT_USERNAME:
            username = conf.DEFAULT_USERNAME
        else:
            print("Need to give username")
            sys.exit(1)
    if "ADFS_DEFAULT_PASSWORD" in environ and environ["ADFS_DEFAULT_PASSWORD"]:
        password = environ["ADFS_DEFAULT_PASSWORD"]
    else:
        password = getpass()

    try:
        assertion, awsroles = saml.get_saml_assertion(username, password, conf)
    except saml.SamlException as e:
        print(e)
        sys.exit(1)

    # Overwrite and delete the credential variables, just for safety
    username = "******"
    password = "******"
    del username
    del password
    role_arn = None
    if conf.NO_PROMPT and conf.ROLE_ARN:
        for awsrole in awsroles:
            if awsrole.startswith(conf.ROLE_ARN + ","):
                role_arn = conf.ROLE_ARN
                principal_arn = awsrole.split(",")[1]
        if not role_arn:
            role_arn, principal_arn = select_role(awsroles)
    else:
        # If I have more than one role, ask the user which one they want,
        # otherwise just proceed
        role_arn, principal_arn = select_role(awsroles)

    if not role_arn:
        print("No valid role found in assertions")
        print(awsroles)
        sys.exit(3)
    # Use the assertion to get an AWS STS token using Assume Role with SAML
    token = sts().assume_role_with_saml(
        RoleArn=role_arn,
        PrincipalArn=principal_arn,
        SAMLAssertion=assertion,
        DurationSeconds=conf.DURATION,
    )
    credentials.write(token, conf.PROFILE)
Esempio n. 5
0
def session_token(duration_minutes=60, token_arn=None, token_value=None):
    if "AWS_SESSION_TOKEN" in os.environ:
        return None
    args = {"DurationSeconds": 3600}

    if duration_minutes:
        args["DurationSeconds"] = duration_minutes * 60
    if token_arn and token_value:
        args["SerialNumber"] = token_arn
        args["TokenCode"] = token_value

    ret = sts().get_session_token(**args)
    if "Credentials" not in ret:
        return None
    else:
        return ret["Credentials"]
Esempio n. 6
0
def main():
    """Log into LastPass, get SAML auth, assume role, and write tokens into credentials file"""
    conf = init()

    if conf.VERBOSE:
        logging.getLogger('lastpass_aws_login').setLevel(logging.DEBUG)

    username = None
    # Get the federated credentials from the user
    if not conf.NO_PROMPT:
        sys.stdout.write("Username [" + conf.DEFAULT_USERNAME + "]: ")
        username = input()
    if not username:
        if conf.DEFAULT_USERNAME:
            username = conf.DEFAULT_USERNAME
        else:
            print("Need to give username")
            sys.exit(1)
    otp = None
    if "LASTPASS_DEFAULT_PASSWORD" in environ and environ[
            "LASTPASS_DEFAULT_PASSWORD"]:
        password = environ["LASTPASS_DEFAULT_PASSWORD"]
    else:
        password = getpass()
    if "LASTPASS_DEFAULT_OTP" in environ and environ["LASTPASS_DEFAULT_OTP"]:
        otp = environ["LASTPASS_DEFAULT_OTP"]

    username = binary_type(username)
    password = binary_type(password)
    lastpass_session = LastPass('https://lastpass.com')

    try:
        lastpass_session.login(username, password, otp=otp)
    except LastPassIncorrectOtpError:
        mfa = input('MFA: ')

        try:
            lastpass_session.login(username, password, otp=mfa)
        except LastPassIncorrectOtpError:
            sys.exit('Invalid MFA code')
    except LastPassCredentialsError:
        sys.exit('Invalid username or password')
    except LastPassError as error:
        # don't display stack trace but still exit and print error message
        sys.exit(str(error))

    assertion = lastpass_session.get_saml_token(conf.SAML_ID)

    awsroles = get_saml_aws_roles(base64.b64decode(assertion))
    # Overwrite and delete the credential variables, just for safety
    username = "******"
    password = "******"
    del username
    del password
    role_arn = None
    if conf.NO_PROMPT and conf.ROLE_ARN:
        for awsrole in awsroles:
            if awsrole.startswith(conf.ROLE_ARN + ","):
                role_arn = conf.ROLE_ARN
                principal_arn = awsrole.split(",")[1]
        if not role_arn:
            role_arn, principal_arn = select_role(awsroles)
    else:
        # If I have more than one role, ask the user which one they want,
        # otherwise just proceed
        role_arn, principal_arn = select_role(awsroles)

    if not role_arn:
        print("No valid role found in assertions")
        print(awsroles)
        sys.exit(3)
    # Use the assertion to get an AWS STS token using Assume Role with SAML
    token = sts().assume_role_with_saml(
        RoleArn=role_arn,
        PrincipalArn=principal_arn,
        SAMLAssertion=assertion,
        DurationSeconds=conf.DURATION,
    )
    credentials.write(token, conf.PROFILE)