Ejemplo n.º 1
0
        virtual public string PrepMode_CreateRole(AmazonIdentityManagementServiceClient iamClient, string roleName,
                                                  string policyText, string trustRelationshipText)
        {
            var roleArn = String.Empty;

            // Use the CreateRoleRequest object to define the role. The AssumeRolePolicyDocument property should be
            // set to the value of the trustRelationshipText parameter.

            var createRoleRequest = new CreateRoleRequest
            {
                AssumeRolePolicyDocument = trustRelationshipText,
                RoleName = roleName
            };

            roleArn = iamClient.CreateRole(createRoleRequest).Role.Arn;

            // Use the PutRolePolicyRequest object to define the request. Select whatever policy name you would like.
            // The PolicyDocument property is there the policy is described.
            var putRolePolicyRequest = new PutRolePolicyRequest
            {
                RoleName       = roleName,
                PolicyName     = String.Format("{0}_policy", roleName),
                PolicyDocument = policyText
            };

            iamClient.PutRolePolicy(putRolePolicyRequest);

            return(roleArn);
        }
Ejemplo n.º 2
0
        private static void CreateRole(String RoleName, String PolicyDocumentFile, String Path = null)
        {
            if (String.IsNullOrEmpty(Token))
            {
                stsClient = new AmazonIdentityManagementServiceClient(AccessKeyId, SecretKey, iamconfig);
            }
            else
            {
                stsClient = new AmazonIdentityManagementServiceClient(AccessKeyId, SecretKey, Token, iamconfig);
            }

            CreateRoleRequest Req = new CreateRoleRequest();

            if (File.Exists(PolicyDocumentFile))
            {
                String policy = File.ReadAllText(PolicyDocumentFile);
                Req.RoleName = RoleName;
                Req.AssumeRolePolicyDocument = policy;
                if (!string.IsNullOrEmpty(Path))
                {
                    Req.Path = Path;
                }

                CreateRoleResponse Response = stsClient.CreateRole(Req);
                Console.WriteLine("Role created successfully");
            }
            else
            {
                Console.WriteLine("Assertion file missing");
            }
        }
        public static Role CreateRoleToAssume(this AmazonIdentityManagementServiceClient client, User user)
        {
            var roleName = "assume-role-" + DateTime.Now.ToFileTime();

            var role = client.CreateRole(new CreateRoleRequest
            {
                RoleName = roleName,
                AssumeRolePolicyDocument = @"{
                  ""Statement"":
                  [
                    {
                      ""Principal"":{""AWS"":""{AccountId}""},
                      ""Effect"":""Allow"",
                      ""Action"":[""sts:AssumeRole""]
                    }
                  ]
                }".Replace("{AccountId}", GetAWSAccountIdFromArn(user))
            }).Role;

            client.PutUserPolicy(new PutUserPolicyRequest
            {
                UserName       = user.UserName,
                PolicyName     = "assume-policy-42",
                PolicyDocument = @"{
                    ""Statement"":{
                        ""Effect"":""Allow"",
                        ""Action"":""sts:AssumeRole"",
                        ""Resource"":""{RoleARN}""
                    }
                }".Replace("{RoleARN}", role.Arn)
            });

            return(role);
        }
Ejemplo n.º 4
0
        public static void CreateRole()
        {
            var roleName = Args.Value("Role");
            var client   = new AmazonIdentityManagementServiceClient();

            client.CreateRole(new CreateRoleRequest
            {
                RoleName = roleName,
                AssumeRolePolicyDocument = @"{""Statement"":[{""Principal"":{""Service"":[""ec2.amazonaws.com""]},""Effect"":""Allow"",""Action"":[""sts:AssumeRole""]}]}"
            });
        }
Ejemplo n.º 5
0
        public void IdentityManagementServiceCreateRole()
        {
            #region eaaa4b5f-51f1-4f73-b0d3-30127040eff8

            var client   = new AmazonIdentityManagementServiceClient();
            var response = client.CreateRole(new CreateRoleRequest
            {
                AssumeRolePolicyDocument = "<Stringified-JSON>",
                Path     = "/",
                RoleName = "Test-Role"
            });

            Role role = response.Role;

            #endregion
        }
Ejemplo n.º 6
0
        public static BasicAWSCredentials CreateTestRoleAndUser(string roleName, string userName, string externalId)
        {
            var assumeRolePolicy = AssumeRolePolicyDocument.Replace("{AccountId}", UtilityMethods.AccountId);

            if (string.IsNullOrEmpty(externalId))
            {
                assumeRolePolicy = assumeRolePolicy.Replace("{Condition}", "");
            }
            else
            {
                assumeRolePolicy = assumeRolePolicy.Replace("{Condition}", AssumeRoleExternalIdCondition.Replace("{ExternalId}", externalId));
            }
            using (var iamClient = new AmazonIdentityManagementServiceClient())
            {
                var role = iamClient.CreateRole(new CreateRoleRequest
                {
                    RoleName = roleName,
                    AssumeRolePolicyDocument = assumeRolePolicy
                }).Role;

                iamClient.PutRolePolicy(new PutRolePolicyRequest
                {
                    RoleName       = role.RoleName,
                    PolicyName     = "allow-list-buckets",
                    PolicyDocument = AllowListBucketsRolePolicyDocument
                });

                var user = iamClient.CreateUser(new CreateUserRequest
                {
                    UserName = userName
                }).User;

                iamClient.PutUserPolicy(new PutUserPolicyRequest
                {
                    UserName       = user.UserName,
                    PolicyName     = "assume-policy-1",
                    PolicyDocument = AssumeRoleUserPolicyDocument
                });

                var accessKey = iamClient.CreateAccessKey(new CreateAccessKeyRequest
                {
                    UserName = userName
                }).AccessKey;

                return(new BasicAWSCredentials(accessKey.AccessKeyId, accessKey.SecretAccessKey));
            }
        }
Ejemplo n.º 7
0
        static string CreateInstanceProfile()
        {
            var roleName = "ec2-sample-" + RESOURCDE_POSTFIX;
            var client   = new AmazonIdentityManagementServiceClient();

            client.CreateRole(new CreateRoleRequest
            {
                RoleName = roleName,
                AssumeRolePolicyDocument = @"{""Statement"":[{""Principal"":{""Service"":[""ec2.amazonaws.com""]},""Effect"":""Allow"",""Action"":[""sts:AssumeRole""]}]}"
            });

            var statement = new Amazon.Auth.AccessControlPolicy.Statement(Amazon.Auth.AccessControlPolicy.Statement.StatementEffect.Allow);

            statement.Actions.Add(S3ActionIdentifiers.AllS3Actions);
            statement.Resources.Add(new Resource("*"));

            var policy = new Policy();

            policy.Statements.Add(statement);

            client.PutRolePolicy(new PutRolePolicyRequest
            {
                RoleName       = roleName,
                PolicyName     = "S3Access",
                PolicyDocument = policy.ToJson()
            });

            var response = client.CreateInstanceProfile(new CreateInstanceProfileRequest
            {
                InstanceProfileName = roleName
            });

            client.AddRoleToInstanceProfile(new AddRoleToInstanceProfileRequest
            {
                InstanceProfileName = roleName,
                RoleName            = roleName
            });

            return(response.InstanceProfile.Arn);
        }
Ejemplo n.º 8
0
        public static void Test(string identityProvider)
        {
            // Login with credentials to create the role
            // credentials are defined in app.config
            var    iamClient          = new AmazonIdentityManagementServiceClient();
            string providerURL        = null,
                   providerAppIdName  = null,
                   providerUserIdName = null,
                   providerAppId      = null;


            switch (identityProvider)
            {
            case "Facebook":
                providerURL        = "graph.facebook.com";
                providerAppIdName  = "app_id";
                providerUserIdName = "id";
                break;

            case "Google":
                providerURL        = "accounts.google.com";
                providerAppIdName  = "aud";
                providerUserIdName = "sub";
                break;

            case "Amazon":
                providerURL        = "www.amazon.com";
                providerAppIdName  = "app_id";
                providerUserIdName = "user_id";
                break;
            }

            //identity provider specific AppId is loaded from app.config (e.g)
            //  FacebookProviderAppId. GoogleProviderAppId, AmazonProviderAppId
            providerAppId = ConfigurationManager.AppSettings[identityProvider +
                                                             "ProviderAppId"];

            // Since the string is passed to String.Format, '{' & '}' has to be escaped.
            // Policy document specifies who can invoke AssumeRoleWithWebIdentity
            string trustPolicyTemplate = @"{{
                  ""Version"": ""2012-10-17"",
                  ""Statement"": [
                        {{
                              ""Effect"": ""Allow"",
                              ""Principal"": {{ ""Federated"": ""{1}"" }},
                              ""Action"": ""sts:AssumeRoleWithWebIdentity"",
                              ""Condition"": {{
                                    ""StringEquals"": {{""{1}:{2}"": ""{3}""}}
                              }}
                        }}
                  ]
                }}";

            // Defines what permissions to grant when AssumeRoleWithWebIdentity is called
            string accessPolicyTemplate = @"{{
                    ""Version"": ""2012-10-17"",
                    ""Statement"": [
                    {{
                        ""Effect"":""Allow"",
                        ""Action"":[""s3:GetObject"", ""s3:PutObject"", ""s3:DeleteObject""],
                        ""Resource"": [
                                ""arn:aws:s3:::federationtestbucket/{0}/${{{1}:{4}}}"",
                                ""arn:aws:s3:::federationtestbucket/{0}/${{{1}:{4}}}/*""
                        ]
                    }}
                    ]
                }}";

            // Create Trust policy
            CreateRoleRequest createRoleRequest = new CreateRoleRequest
            {
                RoleName = "federationtestrole",
                AssumeRolePolicyDocument = string.Format(trustPolicyTemplate,
                                                         identityProvider,
                                                         providerURL,
                                                         providerAppIdName,
                                                         providerAppId)
            };

            Console.WriteLine("\nTrust Policy Document:\n{0}\n",
                              createRoleRequest.AssumeRolePolicyDocument);
            CreateRoleResponse createRoleResponse = iamClient.CreateRole(createRoleRequest);

            // Create Access policy (Permissions)
            PutRolePolicyRequest putRolePolicyRequest = new PutRolePolicyRequest
            {
                PolicyName     = "federationtestrole-rolepolicy",
                RoleName       = "federationtestrole",
                PolicyDocument = string.Format(accessPolicyTemplate,
                                               identityProvider,
                                               providerURL,
                                               providerAppIdName,
                                               providerAppId,
                                               providerUserIdName)
            };

            Console.WriteLine("\nAccess Policy Document (Permissions):\n{0}\n",
                              putRolePolicyRequest.PolicyDocument);
            PutRolePolicyResponse putRolePolicyResponse = iamClient.PutRolePolicy(
                putRolePolicyRequest);

            // Sleep for the policy to replicate
            System.Threading.Thread.Sleep(5000);
            AmazonS3Config config = new AmazonS3Config
            {
                ServiceURL     = "s3.amazonaws.com",
                RegionEndpoint = Amazon.RegionEndpoint.USEast1
            };

            Federation federationTest = new Federation();
            AssumeRoleWithWebIdentityResponse assumeRoleWithWebIdentityResponse = null;

            switch (identityProvider)
            {
            case "Facebook":
                assumeRoleWithWebIdentityResponse =
                    federationTest.GetTemporaryCredentialUsingFacebook(
                        providerAppId,
                        createRoleResponse.Role.Arn);
                break;

            case "Google":
                assumeRoleWithWebIdentityResponse =
                    federationTest.GetTemporaryCredentialUsingGoogle(
                        providerAppId,
                        createRoleResponse.Role.Arn);

                //Uncomment to perform two step process
                //assumeRoleWithWebIdentityResponse =
                //    federationTest.GetTemporaryCredentialUsingGoogle(
                //            providerAppId,
                //            ConfigurationManager.AppSettings["GoogleProviderAppIdSecret"],
                //            createRoleResponse.Role.Arn);
                break;

            case "Amazon":
                assumeRoleWithWebIdentityResponse =
                    federationTest.GetTemporaryCredentialUsingAmazon(
                        ConfigurationManager.AppSettings["AmazonProviderClientId"],
                        createRoleResponse.Role.Arn);
                break;
            }

            S3Test s3Test = new S3Test();

            s3Test.CreateS3Bucket("federationtestbucket",
                                  identityProvider + "/" +
                                  assumeRoleWithWebIdentityResponse.SubjectFromWebIdentityToken,
                                  assumeRoleWithWebIdentityResponse.Credentials, config);

            DeleteRolePolicyResponse deleteRolePolicyResponse =
                iamClient.DeleteRolePolicy(new DeleteRolePolicyRequest
            {
                PolicyName = "federationtestrole-rolepolicy",
                RoleName   = "federationtestrole"
            });

            DeleteRoleResponse deleteRoleResponse =
                iamClient.DeleteRole(new DeleteRoleRequest
            {
                RoleName = "federationtestrole"
            });
        }
        public void GenerateDatasetTest()
        {
            var iamClient = new AmazonIdentityManagementServiceClient();
            var snsClient = new AmazonSimpleNotificationServiceClient();
            var s3Client  = new AmazonS3Client();

            string bucketName = null;
            string topicArn   = null;
            Role   role       = null;

            try
            {
                bucketName = UtilityMethods.GenerateName("GenerateDatasetTestBucket");
                s3Client.PutBucket(bucketName);

                var roleName   = UtilityMethods.GenerateName("GenerateDatasetTestRole");
                var policyName = "MarketplacePolicy";
                // Create a role with trust policy
                role = iamClient.CreateRole(new CreateRoleRequest
                {
                    RoleName = roleName,
                    AssumeRolePolicyDocument = TrustPolicy
                }).Role;

                // Set access policy
                iamClient.PutRolePolicy(new PutRolePolicyRequest
                {
                    RoleName       = roleName,
                    PolicyDocument = AccessPolicy,
                    PolicyName     = policyName
                });

                var snsTopicName = UtilityMethods.GenerateName("GenerateDatasetTestTopic");
                topicArn = snsClient.CreateTopic(snsTopicName).TopicArn;

                // Throws an error as this account does not have any reports
                Utils.AssertExtensions.ExpectException <AmazonAWSMarketplaceCommerceAnalyticsException>
                    (() =>
                    Client.GenerateDataSet(new GenerateDataSetRequest
                {
                    DataSetPublicationDate  = DateTime.Now,
                    DataSetType             = DataSetType.DailyBusinessFees,
                    DestinationS3BucketName = bucketName,
                    SnsTopicArn             = topicArn,
                    RoleNameArn             = role.Arn
                })
                    );
            }
            finally
            {
                s3Client.DeleteBucket(bucketName);

                if (role != null)
                {
                    iamClient.DeleteRolePolicy(new DeleteRolePolicyRequest
                    {
                        PolicyName = "MarketplacePolicy",
                        RoleName   = role.RoleName
                    });

                    iamClient.DeleteRole(new DeleteRoleRequest
                    {
                        RoleName = role.RoleName
                    });
                }

                if (topicArn != null)
                {
                    snsClient.DeleteTopic(topicArn);
                }
            }
        }