public async Task Can_Create_A_Role()
        {
            // Arrange
            var regionalEndpoint = RegionEndpoint.EUWest1;
            var amazonIdentityManagementServiceClient = new AmazonIdentityManagementServiceClient(regionalEndpoint);
            var amazonSecurityTokenServiceClient      = new AmazonSecurityTokenServiceClient(regionalEndpoint);
            var fakePolicyRepository     = new FakePolicyTemplateRepository();
            var identityManagementClient = new IdentityManagementServiceClient(new AmazonIdentityManagementServiceWrapper(amazonIdentityManagementServiceClient));


            var awsIdentityClient = new AwsIdentityCommandClient(
                amazonIdentityManagementServiceClient,
                amazonSecurityTokenServiceClient,
                fakePolicyRepository,
                identityManagementClient
                );

            var roleName = RoleName.Create("test-role-do-delete-33");
            var role     = await awsIdentityClient.EnsureRoleExistsAsync(roleName);

            try
            {
                // Act


                // Assert
            }
            finally
            {
                await identityManagementClient.DeleteRoleAsync(roleName);
            }
        }
        /// <summary>
        /// Used to modify cloudformation cross account artifacts to bucket owner full access.
        /// </summary>
        /// <param name="jobEvent">CodePipeline event.</param>
        /// <param name="context">Lambda Context</param>
        /// <returns>Job success of the Lambda</returns>
        public async Task <AmazonWebServiceResponse> FixCloudFormationOutputArtifactAcl(CodePipelineJobEvent jobEvent, ILambdaContext context)
        {
            var jobId = jobEvent.CodePipelineJob.Id;

            context.Logger.LogLine($"JobId: {jobId}");

            using (var codePipelineClient = new AmazonCodePipelineClient())
                using (var stsClient = new AmazonSecurityTokenServiceClient())
                {
                    try
                    {
                        var jobData = jobEvent.CodePipelineJob.Data;

                        // Assume the role in the cloudformation account that screwed up the bucket permissions
                        // for the output object
                        var userParameters = jobData.ActionConfiguration.Configuration["UserParameters"];
                        var paramDict      = JsonConvert.DeserializeObject <Dictionary <string, string> >(userParameters);
                        var roleArn        = paramDict["RoleArn"];

                        var assumeRoleRequest = new AssumeRoleRequest
                        {
                            RoleArn         = roleArn,
                            RoleSessionName = "codepipeline",
                            DurationSeconds = 900
                        };
                        var assumeRoleResponse = await stsClient.AssumeRoleAsync(assumeRoleRequest);

                        // Setup an S3 Client with the sts creds
                        var s3Client = new AmazonS3Client(assumeRoleResponse.Credentials);

                        // Update the ACLs of the input artifacts
                        foreach (var inputArtifact in jobData.InputArtifacts)
                        {
                            var bucketName = inputArtifact.Location.S3Location.BucketName;
                            var bucketKey  = inputArtifact.Location.S3Location.ObjectKey;
                            context.Logger.LogLine($"Fixing {bucketName}/{bucketKey}");

                            var putObjectAclRequest = new PutACLRequest
                            {
                                BucketName = bucketName,
                                CannedACL  = S3CannedACL.BucketOwnerFullControl,
                                Key        = bucketKey
                            };
                            await s3Client.PutACLAsync(putObjectAclRequest);
                        }

                        // Send the success response
                        var successResultRequest = new PutJobSuccessResultRequest
                        {
                            JobId = jobId
                        };
                        return(await codePipelineClient.PutJobSuccessResultAsync(successResultRequest));
                    }
                    catch (Exception ex)
                    {
                        // Send the failure response and log
                        return(await DoException(codePipelineClient, ex, jobId, context));
                    }
                }
        }
예제 #3
0
        protected override CredentialsRefreshState GenerateNewCredentials()
        {
            var configuredRegion = AWSConfigs.AWSRegion;
            var region           = string.IsNullOrEmpty(configuredRegion) ? DefaultSTSClientRegion : RegionEndpoint.GetBySystemName(configuredRegion);

            Amazon.SecurityToken.Model.Credentials cc = null;
            try
            {
                var stsConfig = ServiceClientHelpers.CreateServiceConfig(ServiceClientHelpers.STS_ASSEMBLY_NAME, ServiceClientHelpers.STS_SERVICE_CONFIG_NAME);
                stsConfig.RegionEndpoint = region;

                var stsClient = new AmazonSecurityTokenServiceClient(new AnonymousAWSCredentials());

                OidcToken oidcToken = SourceCredentials.GetOidcTokenAsync(OidcTokenOptions.FromTargetAudience(TargetAudience).WithTokenFormat(OidcTokenFormat.Standard)).Result;

                TargetAssumeRoleRequest.WebIdentityToken = oidcToken.GetAccessTokenAsync().Result;

                AssumeRoleWithWebIdentityResponse sessionTokenResponse = stsClient.AssumeRoleWithWebIdentityAsync(TargetAssumeRoleRequest).Result;

                cc = sessionTokenResponse.Credentials;
                _logger.InfoFormat("New credentials created for assume role that expire at {0}", cc.Expiration.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", CultureInfo.InvariantCulture));
                return(new CredentialsRefreshState(new ImmutableCredentials(cc.AccessKeyId, cc.SecretAccessKey, cc.SessionToken), cc.Expiration));
            }
            catch (Exception e)
            {
                var msg       = "Error exchanging Google OIDC token for AWS STS ";
                var exception = new InvalidOperationException(msg, e);
                Logger.GetLogger(typeof(GoogleCompatCredentials)).Error(exception, exception.Message);
                throw exception;
            }
        }
예제 #4
0
        public void SecurityTokenServiceGetFederationToken()
        {
            #region to-get-temporary-credentials-for-a-role-by-using-getfederationtoken-1480540749900

            var client   = new AmazonSecurityTokenServiceClient();
            var response = client.GetFederationToken(new GetFederationTokenRequest
            {
                DurationSeconds = 3600,
                Name            = "testFedUserSession",
                Policy          = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Stmt1\",\"Effect\":\"Allow\",\"Action\":\"s3:ListAllMyBuckets\",\"Resource\":\"*\"}]}",
                Tags            = new List <Tag> {
                    new Tag {
                        Key   = "Project",
                        Value = "Pegasus"
                    },
                    new Tag {
                        Key   = "Cost-Center",
                        Value = "98765"
                    }
                }
            });

            Credentials   credentials      = response.Credentials;
            FederatedUser federatedUser    = response.FederatedUser;
            int           packedPolicySize = response.PackedPolicySize;

            #endregion
        }
예제 #5
0
        static async Task Renew()
        {
            Log.Info("Requesting AssumeRole: " + RoleArn + "...");

            var request = new AssumeRoleRequest
            {
                RoleArn         = RoleArn,
                DurationSeconds = (int)12.Hours().TotalSeconds,
                ExternalId      = "Pod",
                RoleSessionName = "Pod"
            };

            try
            {
                using (var client = new AmazonSecurityTokenServiceClient())
                {
                    var response = await client.AssumeRoleAsync(request);

                    Log.Debug("AssumeRole response code: " + response.HttpStatusCode);
                    var credentials = response.Credentials;

                    FallbackCredentialsFactory.Reset();
                    FallbackCredentialsFactory.CredentialsGenerators.Insert(0, () => credentials);

                    Log.Debug("Obtained assume role credentials.");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Submitting Assume Role request failed.");
                throw;
            }
        }
예제 #6
0
        public TemporaryUploadCredentials GenerateTemporaryUploadCredentials()
        {
            return(base.ExecuteFunction("GenerateTemporaryUploadCredentials", delegate()
            {
                Credentials credentials = this.Cache15.PerLifetime("GetSessionToken", delegate()
                {
                    // Cache is every 15 minutes, we set the expire every 30, we're good. :)

                    using (var client = new AmazonSecurityTokenServiceClient(this.AmazonKeyID, this.AmazonSecret, RegionEndpoint.USEast1))
                    {
                        GetSessionTokenResponse response = client.GetSessionToken(new GetSessionTokenRequest
                        {
                            DurationSeconds = (int)TimeSpan.FromMinutes(30).TotalSeconds,
                        });

                        if (response == null || response.HttpStatusCode != System.Net.HttpStatusCode.OK || response.Credentials == null)
                        {
                            throw new UIException("Unable to generate File Upload Credentials. Please try again in a few moments");
                        }
                        return response.Credentials;
                    }
                });

                return new TemporaryUploadCredentials()
                {
                    bucket = this.AmazonBucket,
                    access_key_id = credentials.AccessKeyId,
                    secret_access_key = credentials.SecretAccessKey,
                    session_token = credentials.SessionToken,
                };
            }));
        }
예제 #7
0
        private async Task <Credentials> GetTemporaryCredentials(
            string accessKeyId, string secretAccessKeyId)
        {
            AmazonSecurityTokenServiceClient stsClient =
                new AmazonSecurityTokenServiceClient(accessKeyId,
                                                     secretAccessKeyId);

            GetSessionTokenRequest getSessionTokenRequest =
                new GetSessionTokenRequest();

            getSessionTokenRequest.DurationSeconds = 7200; // seconds

            GetSessionTokenResponse sessionTokenResponse =
                await stsClient.GetSessionTokenAsync(getSessionTokenRequest);

            Credentials credentials = sessionTokenResponse.Credentials;

            //SessionAWSCredentials sessionCredentials =
            //    new SessionAWSCredentials(credentials.AccessKeyId,
            //                              credentials.SecretAccessKey,
            //                              credentials.SessionToken);


            return(credentials);
        }
        public SessionAWSCredentials GetSamlRoleCredentails(string samlAssertion, string awsRole)
        {
            string[] role = awsRole.Split(',');

            AssumeRoleWithSAMLRequest samlRequest = new AssumeRoleWithSAMLRequest();

            samlRequest.SAMLAssertion   = samlAssertion;
            samlRequest.RoleArn         = role[1];
            samlRequest.PrincipalArn    = role[0];
            samlRequest.DurationSeconds = 3600;

            AmazonSecurityTokenServiceClient sts;
            AssumeRoleWithSAMLResponse       samlResponse;

            try {
                sts          = new AmazonSecurityTokenServiceClient();
                samlResponse = sts.AssumeRoleWithSAML(samlRequest);
            }
            catch
            {
                sts          = new AmazonSecurityTokenServiceClient("a", "b", "c");
                samlResponse = sts.AssumeRoleWithSAML(samlRequest);
            }

            SessionAWSCredentials sessionCredentials = new SessionAWSCredentials(
                samlResponse.Credentials.AccessKeyId,
                samlResponse.Credentials.SecretAccessKey,
                samlResponse.Credentials.SessionToken);

            return(sessionCredentials);
        }
        private void CreateAndCheckTestBucket()
        {
            TestBucketIsReady = false;
            USEast1Client     = new AmazonS3Client(RegionEndpoint.USEast1);
            USWest1Client     = new AmazonS3Client(RegionEndpoint.USWest1);
            var sessionCredentials = new AmazonSecurityTokenServiceClient().GetSessionToken().Credentials;

            USEast1ClientWithSessionCredentials = new AmazonS3Client(sessionCredentials, RegionEndpoint.USEast1);

            TestBucket = USWest1Client.ListBuckets().Buckets.Find(bucket => bucket.BucketName.StartsWith(BucketPrefix));
            if (TestBucket == null)
            {
                // add ticks to bucket name because the bucket namespace is shared globally
                var bucketName = BucketPrefix + DateTime.Now.Ticks;
                // Create the bucket but don't run the test.
                // If the bucket is ready the next time this test runs we'll test then.
                USWest1Client.PutBucket(new PutBucketRequest()
                {
                    BucketRegion = S3Region.USW1,
                    BucketName   = bucketName,
                });
            }
            else if (TestBucket.CreationDate.AddHours(TemporaryRedirectMaxExpirationHours) < DateTime.Now)
            {
                BucketRegionDetector.BucketRegionCache.Clear();
                TestBucketIsReady = true;
            }
        }
예제 #10
0
        private void AWSAssumeRole(FacebookDemoModel facebookDemoModel)
        {
            // This is the Facebook token that we got from authenticating with Facebook
            String facebookToken = facebookDemoModel.FacebookToken;

            // Create AWS Security Token Service client object with anonymous credential.  This methods is not using any AWS long term key or any other type of credential.
            AmazonSecurityTokenServiceClient awsSTSClient = new AmazonSecurityTokenServiceClient(new Amazon.Runtime.AnonymousAWSCredentials());

            // Set attribute to pass to the Security Token Service client using the AssumeRoleWithWebIdentityRequest model
            Amazon.SecurityToken.Model.AssumeRoleWithWebIdentityRequest myWebRequest = new Amazon.SecurityToken.Model.AssumeRoleWithWebIdentityRequest();
            myWebRequest.ProviderId       = "graph.facebook.com";                         // Set provider to Facebook
            myWebRequest.RoleSessionName  = "StuzioDemoSession";                          // Set role session name for tracking - Name can be anything.
            myWebRequest.WebIdentityToken = facebookToken;                                // Set the identity token to be the token we got from Facebook log in
            myWebRequest.RoleArn          = "arn:aws:iam::01234567890:role/YourRoleName"; // Set the AWS role in the specified account with role's Amazon Resource Name.   Example: arn:aws:iam::081274447123:role/StuzioWebUserRole
            myWebRequest.DurationSeconds  = 3600;                                         // Set the durtion of session.

            // Using the model with attributes set, assume the role with web identity.
            Amazon.SecurityToken.Model.AssumeRoleWithWebIdentityResponse awsResponse = awsSTSClient.AssumeRoleWithWebIdentity(myWebRequest);

            // Get the response from AWS once Facebook user assumes a role.  Set the model data to display on UI
            facebookDemoModel.AWSAccessKeyID     = awsResponse.Credentials.AccessKeyId;
            facebookDemoModel.AWSSecretAccessKey = awsResponse.Credentials.SecretAccessKey;
            facebookDemoModel.AWSSessionToken    = awsResponse.Credentials.SessionToken;

            return;
        }
예제 #11
0
        protected override void ProcessRecord()
        {
            try
            {
                string mfaDevice       = Environment.GetEnvironmentVariable("DEVOPS_AWS_MFA_DEVICE");
                string devopsAccessKey = Environment.GetEnvironmentVariable("DEVOPS_AWS_ACCESS_KEY_ID");
                string devopsSecretKey = Environment.GetEnvironmentVariable("DEVOPS_AWS_SECRET_ACCESS_KEY");
                AmazonSecurityTokenServiceClient stsClient = string.IsNullOrEmpty(devopsAccessKey)
                    ? new AmazonSecurityTokenServiceClient()
                    : new AmazonSecurityTokenServiceClient(new BasicAWSCredentials(devopsAccessKey, devopsSecretKey));

                using (stsClient)
                {
                    GetSessionTokenRequest request = new GetSessionTokenRequest
                    {
                        DurationSeconds = Duration,
                        SerialNumber    = mfaDevice,
                        TokenCode       = MFAToken
                    };

                    Task <GetSessionTokenResponse> response = stsClient.GetSessionTokenAsync(request);
                    response.Wait(1000);

                    WriteObject(response.Result.Credentials);
                }
            }
            catch (Exception exception)
            {
                ThrowTerminatingError(new ErrorRecord(new Exception("Error getting session token", exception), "Error getting session token", ErrorCategory.InvalidOperation, null));
            }
        }
        public AssumeRoleResponse GetTemporaryCredentials(string awsAccount)
        {
            try
            {
                using (var stsClient = new AmazonSecurityTokenServiceClient())
                {
                    LambdaLogger.Log($"Begin assume role for AWS account with ID {awsAccount}");
                    AssumeRoleRequest request = new AssumeRoleRequest
                    {
                        RoleArn         = $"arn:aws:iam::{awsAccount}:role/{Environment.GetEnvironmentVariable("AWS_ROLE_NAME_FOR_STS_API_GATEWAY_GET")}",
                        DurationSeconds = 900, //15 mins, which is the minimum accepted
                        RoleSessionName = "Session-for-retrieving-API-name"
                    };
                    LambdaLogger.Log($"Role ARN in request: {request.RoleArn}");
                    var credentialsResponse = stsClient.AssumeRoleAsync(request).GetAwaiter().GetResult();
                    LambdaLogger.Log($"Credentials for role with ARN {request.RoleArn} retrieved for user - {credentialsResponse.AssumedRoleUser}");

                    return(credentialsResponse);
                }
            }
            catch (Exception ex)
            {
                LambdaLogger.Log($"An error occurred while assuming role for AWS account with ID {awsAccount}. Message: {ex.Message}");
                throw;
            }
        }
예제 #13
0
        public Credentials GetSessionToken(AWSCredentials credentials)
        {
            Credentials sessionCredentials = null;

            using (var stsClient = new AmazonSecurityTokenServiceClient(credentials))
            {
                try
                {
                    var getSessionTokenRequest = new GetSessionTokenRequest()
                    {
                        DurationSeconds = 7200
                    };

                    GetSessionTokenResponse response = stsClient.GetSessionToken(getSessionTokenRequest);

                    sessionCredentials = response.Credentials;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            return(sessionCredentials);
        }
예제 #14
0
        static async Task RunExample()
        {
            // Identity
            var client         = new AmazonSecurityTokenServiceClient();
            var getCallerIdReq = new GetCallerIdentityRequest();
            var caller         = await GetCallerIdentityResponseAsync(client, getCallerIdReq);

            Console.WriteLine($"Caller identity: {caller.Arn} | {caller.Account} | {caller.UserId}");

            // S3
            RegionEndpoint region     = RegionEndpoint.EUCentral1;
            string         bucketName = "dfds.static.content";
            var            s3Client   = new AmazonS3Client(region);

            var s3NewBucket = new PutBucketRequest
            {
                BucketName   = bucketName,
                BucketRegion = S3Region.EUC1,
                CannedACL    = S3CannedACL.Private
            };

            var s3BucketResponse = await s3Client.PutBucketAsync(s3NewBucket);

            var s3PutObjectRequest = new PutObjectRequest
            {
                BucketName  = bucketName,
                Key         = "hello",
                ContentBody = "Hi Pelle!",
                ContentType = "text/plain"
            };

            var s3PutObjectResponse = await s3Client.PutObjectAsync(s3PutObjectRequest);
        }
예제 #15
0
        private AWSCredentials GetSessionCredentials(AWSCredentials credentials)
        {
            using (var stsClient = new AmazonSecurityTokenServiceClient(credentials))
            {
                GetSessionTokenResponse response = null;

                // wait for eventual consistency of user creation
                UtilityMethods.WaitUntil(() =>
                {
                    try
                    {
                        response = stsClient.GetSessionToken();
                        return(true);
                    }
                    catch (AmazonSecurityTokenServiceException e)
                    {
                        if (String.Equals(e.ErrorCode, "InvalidClientTokenId", StringComparison.OrdinalIgnoreCase))
                        {
                            return(false);
                        }
                        else
                        {
                            throw e;
                        }
                    }
                });

                Assert.IsNotNull(response);
                Assert.IsNotNull(response.Credentials);

                return(new SessionAWSCredentials(response.Credentials.AccessKeyId,
                                                 response.Credentials.SecretAccessKey, response.Credentials.SessionToken));
            }
        }
예제 #16
0
        public void TestAssumeRoleCredentials()
        {
            var          clientId    = Guid.NewGuid();
            var          roleArn     = _role.Arn;
            const string sessionName = "NetUser";

            // sleep for IAM data to propagate
            Thread.Sleep(TimeSpan.FromSeconds(10));
            var sts = new AmazonSecurityTokenServiceClient(_userCredentials);

            Thread.Sleep(TimeSpan.FromSeconds(60));
            var request = new AssumeRoleRequest
            {
                RoleArn         = roleArn,
                RoleSessionName = sessionName,
                DurationSeconds = 3600,
                ExternalId      = clientId.ToString()
            };

            // keep this unit test even though STSAssumeRoleAWSCredentials is obsolete
#pragma warning disable 0618
            var credentials = new STSAssumeRoleAWSCredentials(sts, request);

            var client   = new AmazonIdentityManagementServiceClient(credentials);
            var response = client.ListRoles();
            Assert.IsNotNull(response);
        }
예제 #17
0
        internal static async Task <StopInstancesResponse> StopEc2InstanceAsync(IConfiguration Configuration, string User, string AccountName, string InstanceId)
        {
            try
            {
                var accountKey    = LoadAwsAccounts(Configuration).SingleOrDefault(x => x.AccountName == AccountName);
                var accountRegion = RegionEndpoint.GetBySystemName(accountKey.Region);
                var stsClient     = new AmazonSecurityTokenServiceClient();
                var sessionName   = string.Format(ResourceStrings.StopAction, User, accountKey.AccountName, DateTime.Now.Ticks.ToString());
                sessionName = sessionName.Length > 63 ? sessionName.Substring(0, 63) : sessionName;
                var assumeRoleRequest = new AssumeRoleRequest
                {
                    RoleArn         = accountKey.RoleArn,
                    RoleSessionName = sessionName,
                    DurationSeconds = 900
                };
                var stsResponse = await stsClient.AssumeRoleAsync(assumeRoleRequest);

                var instanceIdAsList = new List <string> {
                    InstanceId
                };
                var stopRequest = new StopInstancesRequest(instanceIdAsList);
                var ec2Client   = new AmazonEC2Client(stsResponse.Credentials, accountRegion);
                var response    = ec2Client.StopInstancesAsync(stopRequest);
                ec2Client.Dispose();
                stsClient.Dispose();
                return(await response);
            }
            catch (Exception e)
            {
                throw new Exception(string.Format(ErrorStrings.RebootEc2InstanceError, InstanceId, e.Message), e.InnerException);
            }
        }
예제 #18
0
        /// <summary>
        /// Gets the <see cref="SessionAWSCredentials"/> based on the specified SAML assertion and role.
        /// </summary>
        /// <param name="samlAssertion">The SAML assertion from the identity provider.</param>
        /// <param name="role">The role that the caller is assuming.</param>
        /// <param name="durationInSeconds">The duration for the AWS session credentials in seconds. Default value is 3600 seconds.</param>
        /// <returns>Returns a <see cref="SessionAWSCredentials"/> based on the specified SAML assertion and role.</returns>
        public SessionAWSCredentials GetSessionAwsCredentials(string samlAssertion, string role, int durationInSeconds = 3600)
        {
            var roles = role.Split(',');

            if (roles.Length > 1)
            {
                throw new ArgumentException("An invalid role was specified.");
            }

            var assumeRoleWithSamlRequest = new AssumeRoleWithSAMLRequest
            {
                SAMLAssertion   = samlAssertion,
                PrincipalArn    = roles[0],
                RoleArn         = roles[1],
                DurationSeconds = durationInSeconds
            };

            // Need to create a  BasicAWSCredentials object and pass it to AmazonSecurityTokenServiceClient,
            // otherwise a null reference exception is thrown. Will need to look into this further as to why this happens.
            var basicCredential = new BasicAWSCredentials("", "");

            using (var amazonSecurityTokenServiceClient = new AmazonSecurityTokenServiceClient(basicCredential))
            {
                var amazonRoleWithSamlResponse = amazonSecurityTokenServiceClient.AssumeRoleWithSAML(assumeRoleWithSamlRequest);
                return(new SessionAWSCredentials(amazonRoleWithSamlResponse.Credentials.AccessKeyId,
                                                 amazonRoleWithSamlResponse.Credentials.SecretAccessKey, amazonRoleWithSamlResponse.Credentials.SessionToken));
            }
        }
예제 #19
0
        public async Task <IActionResult> AssumeRoleAsync()
        {
            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                return(new OkObjectResult("you have to sign in to access AWS resources"));
            }

            try
            {
                var assumeRoleRequest = new AssumeRoleWithWebIdentityRequest
                {
                    RoleArn          = "arn:aws:iam::628654266155:role/acme_app_access_s3",
                    RoleSessionName  = "testsession",
                    WebIdentityToken = GetOktaTokenMiddleware.OktaToken,
                };

                var stsServiceClient = new AmazonSecurityTokenServiceClient(new BasicAWSCredentials("****", "*****"), RegionEndpoint.USEast2);
                var response         = await stsServiceClient.AssumeRoleWithWebIdentityAsync(assumeRoleRequest);

                //var response = await stsServiceClient.ListRoles()
                return(new OkObjectResult($"key = {response.Credentials.AccessKeyId}   security = {response.Credentials.SecretAccessKey}"));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
        public static async Task <SessionAWSCredentials> GetTemporaryFederatedCredentialsAsync(string bucketName)
        {
            var config    = new AmazonSecurityTokenServiceConfig();
            var stsClient = new AmazonSecurityTokenServiceClient(config);

            var federationTokenRequest = new GetFederationTokenRequest();

            federationTokenRequest.DurationSeconds = 7200;
            federationTokenRequest.Name            = "User1";
            federationTokenRequest.Policy          = @"{
               ""Statement"":
               [
                 {
                   ""Sid"":""Stmt1311212314284"",
                   ""Action"":[""s3:ListBucket""],
                   ""Effect"":""Allow"",
                   ""Resource"":""arn:aws:s3:::" + bucketName + @"""
                  }
               ]
             }
            ";

            GetFederationTokenResponse federationTokenResponse =
                await stsClient.GetFederationTokenAsync(federationTokenRequest);

            Credentials credentials = federationTokenResponse.Credentials;

            var sessionCredentials = new SessionAWSCredentials(
                credentials.AccessKeyId,
                credentials.SecretAccessKey,
                credentials.SessionToken);

            return(sessionCredentials);
        }
예제 #21
0
        public void TestAssumeRoleCredentials()
        {
            var          clientId    = Guid.NewGuid();
            var          roleArn     = _role.Arn;
            const string sessionName = "NetUser";

            // sleep for IAM data to propagate
            UtilityMethods.Sleep(TimeSpan.FromSeconds(10));
            var sts = new AmazonSecurityTokenServiceClient(_userCredentials);

            UtilityMethods.Sleep(TimeSpan.FromSeconds(60));
            var request = new AssumeRoleRequest
            {
                RoleArn         = roleArn,
                RoleSessionName = sessionName,
                DurationSeconds = 3600,
                ExternalId      = clientId.ToString()
            };

            var credentials = new STSAssumeRoleAWSCredentials(sts, request);

            var client   = new AmazonIdentityManagementServiceClient(credentials);
            var response = client.ListRolesAsync().Result;

            Assert.IsNotNull(response);
        }
예제 #22
0
        public static Credentials GetTemporaryCredentials(string policy)
        {
            var config = new AmazonSecurityTokenServiceConfig
            {
                RegionEndpoint = RegionEndpoint.APSoutheast2
            };
            var client    = new AmazonSecurityTokenServiceClient(config);
            var iamClient = new AmazonIdentityManagementServiceClient(
                RegionEndpoint.APSoutheast2);

            var iamRoleName = EC2InstanceMetadata.GetData("/iam/security-credentials");
            var role        = iamClient.GetRole(
                new GetRoleRequest()
            {
                RoleName = iamRoleName
            });
            var assumeRoleRequest = new AssumeRoleRequest()
            {
                RoleArn         = role.Role.Arn,
                RoleSessionName = Guid.NewGuid().ToString().Replace("-", ""),
                DurationSeconds = 900
            };

            if (!string.IsNullOrEmpty(policy))
            {
                assumeRoleRequest.Policy = policy;
            }

            var assumeRoleResponse =
                client.AssumeRole(assumeRoleRequest);
            var credentials = assumeRoleResponse.Credentials;

            return(credentials);
        }
예제 #23
0
        private static IRestRequest SignWithSTSKeysAndSecurityToken(IRestRequest restRequest, string host, string roleARN, string accessKey, string secretKey)
        {
            AssumeRoleResponse response = null;

            using (var STSClient = new AmazonSecurityTokenServiceClient(accessKey, secretKey, RegionEndpoint.EUWest1))
            {
                var req = new AssumeRoleRequest()
                {
                    RoleArn         = roleARN,
                    DurationSeconds = 950, //put anything you want here
                    RoleSessionName = Guid.NewGuid().ToString()
                };

                response = STSClient.AssumeRoleAsync(req, new CancellationToken()).Result;
            }

            //auth step 3: dönen değerler bizim yeni tokenlarımızı...
            var awsAuthenticationCredentials = new AWSAuthenticationCredentials
            {
                AccessKeyId = response.Credentials.AccessKeyId,
                SecretKey   = response.Credentials.SecretAccessKey,
                Region      = REGION
            };

            restRequest.AddHeader("x-amz-security-token", response.Credentials.SessionToken);
            return(new AWSSigV4Signer(awsAuthenticationCredentials).Sign(restRequest, host));
        }
예제 #24
0
        public async Task AssumeRoleAsync(UserAccountExtended userAccount, UserRoleExtended userRole,
                                          CancellationToken cancellationToken)
        {
            if (userAccount == null)
            {
                throw new ArgumentNullException(nameof(userAccount));
            }
            if (userRole == null)
            {
                throw new ArgumentNullException(nameof(userRole));
            }
            if (cancellationToken == null)
            {
                throw new ArgumentNullException(nameof(cancellationToken));
            }

            using (var stsClient = new AmazonSecurityTokenServiceClient(userAccount.AwsCredentials, _config))
            {
                var request = new AssumeRoleRequest
                {
                    RoleArn         = Role(userRole.AwsAccountId, userRole.Role),
                    RoleSessionName = userRole.AwsAccountLabel
                };

                var role2 = await stsClient.AssumeRoleAsync(request, cancellationToken)
                            .ConfigureAwait(false);

                var tempAccessKeyId     = role2.Credentials.AccessKeyId;
                var tempSessionToken    = role2.Credentials.SessionToken;
                var tempSecretAccessKey = role2.Credentials.SecretAccessKey;
                userRole.AwsCredentials =
                    new SessionAWSCredentials(tempAccessKeyId, tempSecretAccessKey, tempSessionToken);
            }
        }
예제 #25
0
        public CognitoAWSCredentials(string accountId, string identityPoolId, string unAuthRoleArn, string authRoleArn, IAmazonCognitoIdentity cibClient, IAmazonSecurityTokenService stsClient)
        {
            if (string.IsNullOrEmpty(identityPoolId))
            {
                throw new ArgumentNullException("identityPoolId");
            }
            if (cibClient == null)
            {
                throw new ArgumentNullException("cibClient");
            }
            if ((unAuthRoleArn != null || authRoleArn != null) && stsClient == null)
            {
                throw new ArgumentNullException("stsClient");
            }
            AccountId      = accountId;
            IdentityPoolId = identityPoolId;
            UnAuthRoleArn  = unAuthRoleArn;
            AuthRoleArn    = authRoleArn;
            Logins         = new Dictionary <string, string>(StringComparer.Ordinal);
            cib            = (AmazonCognitoIdentityClient)cibClient;
            sts            = (AmazonSecurityTokenServiceClient)stsClient;
            string cachedIdentityId = GetCachedIdentityId();

            if (!string.IsNullOrEmpty(cachedIdentityId))
            {
                UpdateIdentity(cachedIdentityId);
                currentState = GetCachedCredentials();
            }
        }
예제 #26
0
        public async Task CreateAwsCredentialsAsync(UserAccountExtended userAccount, string mfaToken,
                                                    CancellationToken cancellationToken)
        {
            if (userAccount == null)
            {
                throw new ArgumentNullException(nameof(userAccount));
            }
            if (string.IsNullOrWhiteSpace(mfaToken))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(mfaToken));
            }
            if (cancellationToken == null)
            {
                throw new ArgumentNullException(nameof(cancellationToken));
            }

            var basicAwsCredentials = new BasicAWSCredentials(userAccount.UserAccessKey, userAccount.UserSecretKey);

            using (var stsClient = new AmazonSecurityTokenServiceClient(basicAwsCredentials, _config))
            {
                var getSessionTokenRequest = new GetSessionTokenRequest
                {
                    DurationSeconds = 3600,
                    SerialNumber    = $"arn:aws:iam::{userAccount.UserAccountId}:mfa/{userAccount.UserName}",
                    TokenCode       = mfaToken
                };

                var getSessionTokenResponse =
                    await stsClient.GetSessionTokenAsync(getSessionTokenRequest, cancellationToken)
                    .ConfigureAwait(false);

                userAccount.AwsCredentials = getSessionTokenResponse.Credentials;
            }
        }
예제 #27
0
        //--- Methods ---
        protected async Task <(string AccountId, string Region)?> InitializeAwsProfile(string awsProfile, string awsAccountId = null, string awsRegion = null)
        {
            // initialize AWS profile
            if (awsProfile != null)
            {
                // select an alternate AWS profile by setting the AWS_PROFILE environment variable
                Environment.SetEnvironmentVariable("AWS_PROFILE", awsProfile);
            }

            // determine default AWS region
            if ((awsAccountId == null) || (awsRegion == null))
            {
                // determine AWS region and account
                try {
                    var stsClient = new AmazonSecurityTokenServiceClient();
                    var response  = await stsClient.GetCallerIdentityAsync(new GetCallerIdentityRequest());

                    awsAccountId = awsAccountId ?? response.Account;
                    awsRegion    = awsRegion ?? stsClient.Config.RegionEndpoint.SystemName ?? "us-east-1";
                } catch (Exception e) {
                    AddError("unable to determine the AWS Account Id and Region", e);
                    return(null);
                }
            }

            // set AWS region for library and spawned processes
            AWSConfigs.AWSRegion = awsRegion;
            Environment.SetEnvironmentVariable("AWS_REGION", awsRegion);
            Environment.SetEnvironmentVariable("AWS_DEFAULT_REGION", awsRegion);
            return(AccountId : awsAccountId, Region : awsRegion);
        }
예제 #28
0
        public void TestAssumeRole()
        {
            var          clientId    = Guid.NewGuid();
            var          roleArn     = _role.Arn;
            const string sessionName = "NetUser";

            // sleep for IAM data to propagate
            Thread.Sleep(TimeSpan.FromSeconds(10));
            var sts = new AmazonSecurityTokenServiceClient(_userCredentials);

            Thread.Sleep(TimeSpan.FromSeconds(60));
            var result = sts.AssumeRole(new AssumeRoleRequest
            {
                RoleArn         = roleArn,
                RoleSessionName = sessionName,
                DurationSeconds = 3600,
                ExternalId      = clientId.ToString()
            });

            var credentials = result.Credentials;

            var sessionCredentials = new SessionAWSCredentials(credentials.AccessKeyId, credentials.SecretAccessKey, credentials.SessionToken);
            var client             = new AmazonIdentityManagementServiceClient(sessionCredentials);
            var response           = client.ListRoles();

            Assert.IsNotNull(response);

            client   = new AmazonIdentityManagementServiceClient(credentials);
            response = client.ListRoles();
            Assert.IsNotNull(response);
        }
예제 #29
0
        static async Task Main()
        {
            // Create the SecurityToken client and then display the identity of the
            // default user.
            var roleArnToAssume = "arn:aws:iam::123456789012:role/testAssumeRole";

            var client = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient(REGION);

            // Get and display the information about the identity of the default user.
            var callerIdRequest = new GetCallerIdentityRequest();
            var caller          = await client.GetCallerIdentityAsync(callerIdRequest);

            Console.WriteLine($"Original Caller: {caller.Arn}");

            // Create the request to use with the AssumeRoleAsync call.
            var assumeRoleReq = new AssumeRoleRequest()
            {
                DurationSeconds = 1600,
                RoleSessionName = "Session1",
                RoleArn         = roleArnToAssume
            };

            var assumeRoleRes = await client.AssumeRoleAsync(assumeRoleReq);

            // Now create a new client based on the credentials of the caller assuming the role.
            var client2 = new AmazonSecurityTokenServiceClient(credentials: assumeRoleRes.Credentials);

            // Get and display information about the caller that has assumed the defined role.
            var caller2 = await client2.GetCallerIdentityAsync(callerIdRequest);

            Console.WriteLine($"AssumedRole Caller: {caller2.Arn}");
        }
예제 #30
0
        static void Main(string[] args)
        {
            string         accessKey = "AKIAYASBUYUORND23YUN";
            string         secretKey = "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";
            RegionEndpoint region    = RegionEndpoint.APSoutheast2;
            AWSCredentials cred      = new BasicAWSCredentials(accessKey, secretKey);
            IAmazonSecurityTokenService stsClient = new AmazonSecurityTokenServiceClient(cred, region);

            AssumeRoleRequest stsRequest = new AssumeRoleRequest();

            stsRequest.DurationSeconds = 910;
            stsRequest.RoleArn         = "arn:aws:iam::550967231773:role/MyAssumeRole";
            stsRequest.RoleSessionName = "MyAssumeRolesessionFromDotNet";

            AssumeRoleResponse temporaryCred = stsClient.AssumeRoleAsync(stsRequest).Result;

            IAmazonS3 client = new AmazonS3Client(temporaryCred.Credentials, region);

            ListBucketsRequest request = new ListBucketsRequest();

            ListBucketsResponse response = client.ListBucketsAsync(request).Result;

            foreach (S3Bucket b in response.Buckets)
            {
                Console.WriteLine(b.BucketName);
            }

            Console.ReadLine();
        }
        private CredentialsRefreshState Authenticate(ICredentials userCredential, TimeSpan credentialDuration)
        {
            CredentialsRefreshState state;
            SAMLAssertion assertion;

            var configuredRegion = AWSConfigs.AWSRegion;
            var region = string.IsNullOrEmpty(configuredRegion)
                                ? DefaultSTSClientRegion
                                : RegionEndpoint.GetBySystemName(configuredRegion);

            try
            {
                assertion = new SAMLAuthenticationController().GetSAMLAssertion(ProfileData.EndpointSettings.Endpoint.ToString(),
                                                                                userCredential,
                                                                                ProfileData.EndpointSettings.AuthenticationType);
            }
            catch (Exception e)
            {
                throw new AuthenticationFailedException("Authentication failure, unable to obtain SAML assertion.", e);
            }

            try
            {
                using (var stsClient = new AmazonSecurityTokenServiceClient(new AnonymousAWSCredentials(), region))
                {
                    var credentials = assertion.GetRoleCredentials(stsClient, ProfileData.RoleArn, credentialDuration);
                    state = new CredentialsRefreshState(credentials, DateTime.UtcNow + credentialDuration);
                }
            }
            catch (Exception e)
            {
                var wrappedException = new AmazonClientException("Credential generation failed following successful authentication.", e);

                var logger = Logger.GetLogger(typeof(StoredProfileSAMLCredentials));
                logger.Error(wrappedException, wrappedException.Message);

                throw wrappedException;
            }

            return state;
        }