Пример #1
0
        public void TestAssumeRoleProfile(string roleExternalId, string credentialsExternalId,
                                          string mfaSerialNumber, Func <string> mfaTokenCallback, bool expectFailure, bool sessionCredsAsSource)
        {
            try
            {
                // clean up at start in case a test dies in the middle of clean up and is restarted
                IAMTestUtil.CleanupTestRoleAndUser(TestRoleName, TestUserName);

                var roleArn           = "arn:aws:iam::" + UtilityMethods.AccountId + ":role/" + TestRoleName;
                var newCredentials    = IAMTestUtil.CreateTestRoleAndUser(TestRoleName, TestUserName, roleExternalId);
                var sourceCredentials = sessionCredsAsSource ? GetSessionCredentials(newCredentials) : newCredentials;

                var options = new AssumeRoleAWSCredentialsOptions()
                {
                    ExternalId           = credentialsExternalId,
                    MfaSerialNumber      = mfaSerialNumber,
                    MfaTokenCodeCallback = mfaTokenCallback
                };

                var assumeRoleCredentials = new AssumeRoleAWSCredentials(sourceCredentials, roleArn, TestRoleName, options);

                TestCredentials(assumeRoleCredentials, expectFailure);
            }
            finally
            {
                IAMTestUtil.CleanupTestRoleAndUser(TestRoleName, TestUserName);
            }
        }
        private void AssertAssumeRoleCredentialsAreEqual(AssumeRoleAWSCredentials expected, AWSCredentials actualAWSCredentials)
        {
            var actual = actualAWSCredentials as AssumeRoleAWSCredentials;

            Assert.IsNotNull(actual);
            // can't do AreEqual because this contains DateTime.UtcNow.Ticks
            Assert.IsTrue(actual.RoleSessionName.StartsWith("aws-dotnet-sdk-session-"));
            Assert.AreEqual(expected.RoleArn, actual.RoleArn);
            Assert.AreEqual(expected.PreemptExpiryTime, actual.PreemptExpiryTime);
            if (expected.SourceCredentials is AssumeRoleAWSCredentials && actual.SourceCredentials is AssumeRoleAWSCredentials)
            {
                AssertAssumeRoleCredentialsAreEqual(expected.SourceCredentials as AssumeRoleAWSCredentials, actual.SourceCredentials);
            }
            else if (expected.SourceCredentials is FederatedAWSCredentials && actual.SourceCredentials is FederatedAWSCredentials)
            {
                AssertFederatedCredentialsAreEqual(expected.SourceCredentials as FederatedAWSCredentials, actual.SourceCredentials);
            }
            else
            {
                Assert.AreEqual(expected.SourceCredentials, actual.SourceCredentials);
            }
            Assert.AreEqual(expected.Options.DurationSeconds, actual.Options.DurationSeconds);
            Assert.AreEqual(expected.Options.ExternalId, actual.Options.ExternalId);
            Assert.AreEqual(expected.Options.MfaSerialNumber, actual.Options.MfaSerialNumber);
            Assert.AreEqual(expected.Options.MfaTokenCodeCallback, actual.Options.MfaTokenCodeCallback);
            Assert.AreEqual(expected.Options.Policy, actual.Options.Policy);
            Assert.AreEqual(expected.Options.ProxySettings, actual.Options.ProxySettings);
        }
Пример #3
0
        public static T CreateClient()
        {
            var credentials = new AssumeRoleAWSCredentials(new StoredProfileAWSCredentials(), "arn:aws:iam::383514732995:role/SAFE-Dev_role", "AssumeRole");

            //client = new T(credentials, AwsCommon.GetRetionEndpoint("us-east-2"));
            return(client);
        }
Пример #4
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()
            };

            var credentials = new AssumeRoleAWSCredentials(sts, request);

            var client   = new AmazonIdentityManagementServiceClient(credentials);
            var response = client.ListRoles();

            Assert.IsNotNull(response);
        }
Пример #5
0
        public async Task <string> Get()
        {
            string            output     = string.Empty;
            var               sharedFile = new SharedCredentialsFile();
            CredentialProfile devProfile;

            if (sharedFile.TryGetProfile("build", out devProfile))
            {
                BasicAWSCredentials credentials =
                    new BasicAWSCredentials(devProfile.Options.AccessKey, devProfile.Options.SecretKey);
                var assumerole = new AssumeRoleAWSCredentials(credentials, devProfile.Options.RoleArn, "channelsrole");



                IAmazonS3 client = new AmazonS3Client(assumerole, RegionEndpoint.USWest2);

                GetObjectRequest request = new GetObjectRequest();
                request.BucketName = "ch2-sms-startchat-authentication";
                request.Key        = "Token.txt";
                var response = await client.GetObjectAsync(request);

                using (var reader = new StreamReader(response.ResponseStream))
                {
                    output = await reader.ReadToEndAsync();
                }
            }
            return(output);
        }
        /// <exception cref="AggregateException">
        /// If both InstanceProfile and EnvironmentVariable Credentials fail.
        /// Contains AmazonClientExceptions for both InstanceProfile and EnvironmentVariable failures</exception>
        /// <exception cref="AmazonClientException">If Basic (Account) Credentials fail</exception>
        public bool TryGetCredentials(ILog log, out AWSCredentials credentials)
        {
            credentials = null;
            if (Credentials.Type == "account")
            {
                try
                {
                    credentials = new BasicAWSCredentials(Credentials.Account.AccessKey, Credentials.Account.SecretKey);
                }
                // Catching a generic Exception because AWS SDK throws undocumented exceptions.
                catch (Exception e)
                {
                    log.Warn("Unable to authorise credentials, see verbose log for details.");
                    log.Verbose($"Unable to authorise credentials for Account: {e}");
                    return(false);
                }
            }
            else
            {
                try
                {
                    // If not currently running on an EC2 instance,
                    // this will throw an exception.
                    credentials = new InstanceProfileAWSCredentials();
                }
                // Catching a generic Exception because AWS SDK throws undocumented exceptions.
                catch (Exception instanceProfileException)
                {
                    try
                    {
                        // The last attempt is trying to use Environment Variables.
                        credentials = new EnvironmentVariablesAWSCredentials();
                    }
                    // Catching a generic Exception because AWS SDK throws undocumented exceptions.
                    catch (Exception environmentVariablesException)
                    {
                        log.Warn("Unable to authorise credentials, see verbose log for details.");
                        log.Verbose($"Unable to authorise credentials for Instance Profile: {instanceProfileException}");
                        log.Verbose($"Unable to authorise credentials for Environment Variables: {environmentVariablesException}");
                        return(false);
                    }
                }
            }

            if (Role.Type == "assumeRole")
            {
                credentials = new AssumeRoleAWSCredentials(credentials,
                                                           Role.Arn,
                                                           Role.SessionName ?? DefaultSessionName,
                                                           new AssumeRoleAWSCredentialsOptions
                {
                    ExternalId = Role.ExternalId, DurationSeconds = Role.SessionDuration
                });
            }

            return(true);
        }
Пример #7
0
        AWSCredentials ICredentialsProvider.AssumeRole(
            AWSCredentials credentials,
            string role
            )
        {
            var roleCredentials = new AssumeRoleAWSCredentials(
                credentials,
                role,
                Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture));

            return(roleCredentials);
        }
Пример #8
0
        public static async Task <AWSCredentials> AssumeRoleAsync(AWSCredentials credentials, string roleArn,
                                                                  string roleSessionName)
        {
            var assumedCredentials   = new AssumeRoleAWSCredentials(credentials, roleArn, roleSessionName);
            var immutableCredentials = await credentials.GetCredentialsAsync();

            if (string.IsNullOrWhiteSpace(immutableCredentials.Token))
            {
                throw new InvalidOperationException($"Unable to assume role {roleArn}");
            }

            return(assumedCredentials);
        }
Пример #9
0
        private static void TestCredentials(AssumeRoleAWSCredentials assumeRoleCredentials, bool expectFailure)
        {
            ListBucketsResponse response = null;

            using (var client = new AmazonS3Client(assumeRoleCredentials))
            {
                // user/role setup may not be complete
                // so retry for a bit before giving up
                var stopTime = DateTime.Now.AddSeconds(30);
                while (response == null && DateTime.Now < stopTime)
                {
                    var doSleep = true;
                    try
                    {
                        response = client.ListBuckets();
                        Assert.AreEqual(HttpStatusCode.OK, response.HttpStatusCode);
                        doSleep = false;
                    }
                    catch (AmazonClientException)
                    {
                        // no need to retry if we're expecting a failure
                        if (expectFailure)
                        {
                            throw;
                        }
                    }
                    catch (AmazonServiceException)
                    {
                    }

                    if (doSleep)
                    {
                        Thread.Sleep(1000);
                    }
                }
            }

            if (expectFailure)
            {
                Assert.Fail("The test did not receive the expected authentication failure.");
            }
            else
            {
                Assert.IsNotNull(response, "Unable to use AssumeRoleCredentials to successfully complete a request.");
            }
        }
Пример #10
0
        public T Create <T>(IAwsProfile assumeProfile = default) where T : IAmazonService
        {
            AWSCredentials impersonateCredentials = _awsCredentialResolver.Resolve(_options.Value.Impersonate) ?? FallbackCredentialsFactory.GetCredentials();
            AWSCredentials sdkClientCredentials   = impersonateCredentials;

            if (assumeProfile != null)
            {
                var assumeProfileCredentials = _awsCredentialResolver.Resolve(assumeProfile);

                sdkClientCredentials = new AssumeRoleAWSCredentials(impersonateCredentials, assumeProfile.RoleArn, assumeProfileCredentials.Token);
            }

            var clientOfTConstructor = typeof(T).GetConstructor(new[] { typeof(AWSCredentials), typeof(RegionEndpoint) });
            var clientOfT            = (T)clientOfTConstructor.Invoke(new object[] { sdkClientCredentials, RegionEndpoint.GetBySystemName(_options.Value.Region) });

            return(clientOfT);
        }
Пример #11
0
        public KinesisService(KinesisConfig kinesisConfig, UserDataFilterService filterService)
        {
            this.StreamName    = kinesisConfig?.StreamName ?? throw new ArgumentNullException(nameof(kinesisConfig));
            this.filterService = filterService;

            if (!String.IsNullOrEmpty(kinesisConfig.Arn))
            {
                AssumeRoleAWSCredentials credentials = new AssumeRoleAWSCredentials(FallbackCredentialsFactory.GetCredentials(), kinesisConfig.Arn, kinesisConfig.StsRoleSessionName, new AssumeRoleAWSCredentialsOptions
                {
                    DurationSeconds = ChatConfiguration.StsCredentialExpiration
                });
                kinesisClient = new AmazonKinesisClient(credentials);
            }
            else
            {
                kinesisClient = new AmazonKinesisClient();
            }
#if !XRAY2
            string whitelistPath = System.Web.Hosting.HostingEnvironment.MapPath("/AWSWhitelist.json");

            var tracer = new Amazon.XRay.Recorder.Handlers.AwsSdk.AWSSdkTracingHandler(AWSXRayRecorder.Instance, whitelistPath);
            tracer.AddEventHandler(kinesis);
#endif
        }
Пример #12
0
        public static bool CreateClient()
        {
            if (_useDynamoDBLocal)
            {
                //parse ip address and port
                int    i         = _localServiceURL.Contains("://") ? _localServiceURL.IndexOf("://") : -3;
                string ipAddress = _localServiceURL.Substring(i + 3);

                i = ipAddress.Contains(":") ? ipAddress.IndexOf(":") : -1;
                if (i == -1)
                {
                    ShowError("ERROR: Port not found. Please specify a port");
                    return(false);
                }
                string portText = ipAddress.Substring(i + 1);
                ipAddress = ipAddress.Substring(0, i);
                int port = 0;
                if (!int.TryParse(portText, out port))
                {
                    ShowError("ERROR: Port is not a number. Please specify a valid port");
                    return(false);
                }

                // First, check to see whether anyone is listening on the DynamoDB local port
                // (by default, this is port 8000, so if you are using a different port, modify this accordingly)
                bool localFound = false;
                try
                {
                    using (var tcp_client = new TcpClient())
                    {
                        var result = tcp_client.BeginConnect(ipAddress, port, null, null);
                        localFound = result.AsyncWaitHandle.WaitOne(3000); // Wait 3 seconds
                        tcp_client.EndConnect(result);
                    }
                }
                catch
                {
                    localFound = false;
                }
                if (!localFound)
                {
                    ShowError("ERROR: DynamoDB Local does not appear to have been started. Checked port " + port);
                    return(false);
                }

                CredentialProfileStoreChain chain = new CredentialProfileStoreChain();
                AWSCredentials credentials;

                if (!chain.TryGetAWSCredentials(_awsProfile, out credentials))
                {
                    ShowError("Profile {0} not found", _awsProfile);
                    return(false);
                }

                RegionEndpoint region = RegionEndpoint.GetBySystemName(_awsRegion);

                if (region == null)
                {
                    ShowError("Region {0} not found", _awsRegion);
                    return(false);
                }

                // If DynamoDB-Local does seem to be running, so create a client
                ShowInfo("Setting up a DynamoDB-Local client (DynamoDB Local seems to be running)");
                AmazonDynamoDBConfig ddbConfig = new AmazonDynamoDBConfig();
                ddbConfig.ServiceURL = _localServiceURL;

                try
                {
                    //_client = new AmazonDynamoDBClient(ddbConfig);
                    _client = new AmazonDynamoDBClient(credentials, ddbConfig);
                }
                catch (Exception ex)
                {
                    ShowError("FAILED to create a DynamoDBLocal client; " + ex.Message);
                    return(false);
                }
            }

            else
            {
                CredentialProfileStoreChain chain = new CredentialProfileStoreChain();
                AWSCredentials credentials;

                if (!chain.TryGetAWSCredentials(_awsProfile, out credentials))
                {
                    ShowError("Profile {0} not found", _awsProfile);
                    return(false);
                }

                RegionEndpoint region = RegionEndpoint.GetBySystemName(_awsRegion);

                if (region == null)
                {
                    ShowError("Region {0} not found", _awsRegion);
                    return(false);
                }

                //If MFA is enabled on this probile, ask for an access code
                AssumeRoleAWSCredentials assumeCredentials = credentials as AssumeRoleAWSCredentials;
                if (assumeCredentials != null && !string.IsNullOrWhiteSpace(assumeCredentials.Options.MfaSerialNumber))
                {
                    assumeCredentials.Options.MfaTokenCodeCallback = () =>
                    {
                        Console.WriteLine("Enter MFA code: ");
                        return(Console.ReadLine());
                    };
                }

                try
                {
                    ShowInfo("Connecting to DynamoDB with profile {0} in region {1}", _awsProfile, _awsRegion);
                    _client = new AmazonDynamoDBClient(credentials, region);
                }
                catch (Exception ex)
                {
                    ShowError("     FAILED to create a DynamoDB client; " + ex.Message);
                    return(false);
                }
            }
            return(true);
        }
Пример #13
0
        public ActionResult Post()
        {
            try
            {
                var sharedFile = new SharedCredentialsFile();
                CredentialProfile devProfile;
                if (sharedFile.TryGetProfile("dev", out devProfile))
                {
                    var assumeRoleResult = new AssumeRoleAWSCredentials(new SessionAWSCredentials(devProfile.Options.AccessKey,
                                                                                                  devProfile.Options.SecretKey,
                                                                                                  devProfile.Options.Token),
                                                                        devProfile.Options.RoleArn,
                                                                        "channelsrole");


                    String messagetype = Request.Headers["x-amz-sns-message-type"];

                    //If message doesn't have the message type header, don't process it.
                    if (messagetype == null)
                    {
                        return(StatusCode(400));
                    }
                    var message = string.Empty;
                    using (var reader = new StreamReader(Request.Body))
                    {
                        message = reader.ReadToEnd();
                        var sm = Amazon.SimpleNotificationService.Util.Message.ParseMessage(message);

                        // Check the signature and throw an exception if the signature verification fails.
                        if (isMessageSignatureValid(sm.SigningCertURL, sm.Signature, message).Result)
                        {
                            Debug.WriteLine("Signature verification succeeded");
                            if (sm.IsSubscriptionType)
                            {
                                var model = new Amazon.SimpleNotificationService.Model.ConfirmSubscriptionRequest(sm.TopicArn, sm.Token);
                                AmazonSimpleNotificationServiceClient c = new AmazonSimpleNotificationServiceClient(assumeRoleResult, RegionEndpoint.USWest2);
                                c.ConfirmSubscriptionAsync(model).Wait();
                                return(Ok());          // CONFIRM THE SUBSCRIPTION
                            }
                            if (sm.IsNotificationType) // PROCESS NOTIFICATIONS
                            {
                                dynamic json = JObject.Parse(sm.MessageText);
                                //extract value: var s3OrigUrlSnippet = json.input.key.Value as string;
                            }
                        }
                        else
                        {
                            Console.WriteLine(">>Signature verification failed");
                            return(StatusCode(400));
                        }
                    }

                    //do stuff
                    return(Ok(new { }));
                }
                return(Ok(new { }));
            }
            catch (Exception ex)
            {
                //LogIt.E(ex);
                return(StatusCode(500, ex));
            }
        }