Пример #1
0
        private static void UpdateUser(String OldUserName, String NewUserName, String NewPath)
        {
            if (String.IsNullOrEmpty(Token))
            {
                stsClient = new AmazonIdentityManagementServiceClient(AccessKeyId, SecretKey, iamconfig);
            }
            else
            {
                stsClient = new AmazonIdentityManagementServiceClient(AccessKeyId, SecretKey, Token, iamconfig);
            }

            UpdateUserRequest req = new UpdateUserRequest(OldUserName);

            if (!String.IsNullOrEmpty(NewUserName))
            {
                req.NewUserName = NewUserName;
            }

            if (!String.IsNullOrEmpty(NewPath))
            {
                req.NewPath = NewPath;
            }

            try
            {
                UpdateUserResponse response = stsClient.UpdateUser(req);
                Console.WriteLine("User updated");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occured while creating user. " + ex.ToString());
            }
        }
Пример #2
0
        public static void DetachRolePolicy()
        {
            var               client      = new AmazonIdentityManagementServiceClient();
            string            policy      = GenerateRolePolicyDocument();
            CreateRoleRequest roleRequest = new CreateRoleRequest()
            {
                RoleName = "tester",
                AssumeRolePolicyDocument = policy
            };

            var request = new DetachRolePolicyRequest()
            {
                PolicyArn = "arn:aws:iam::123456789:policy/DemoEC2Permissions",
                RoleName  = "tester"
            };

            try
            {
                var response = client.DetachRolePolicy(request);
                Console.WriteLine("Policy DemoEC2Permissions detached from Role 'tester'");
            }
            catch (NoSuchEntityException e)
            {
                Console.WriteLine
                    (e.Message);
            }
            catch (InvalidInputException i)
            {
                Console.WriteLine
                    (i.Message);
            }
        }
Пример #3
0
        private Dictionary <string, string> CanCreateUser(string awsid, string awskey)
        {
            var dict = new Dictionary <string, string>();
            var cl   = new AmazonIdentityManagementServiceClient(awsid, awskey);

            try
            {
                var user = cl.GetUser().User;

                dict["isroot"] = "False"; //user.Arn.EndsWith(":root", StringComparison.Ordinal).ToString();
                dict["arn"]    = user.Arn;
                dict["id"]     = user.UserId;
                dict["name"]   = user.UserName;

                dict["isroot"] = (cl.SimulatePrincipalPolicy(new SimulatePrincipalPolicyRequest()
                {
                    PolicySourceArn = user.Arn, ActionNames = new[] { "iam:CreateUser" }.ToList()
                }).EvaluationResults.First().EvalDecision == PolicyEvaluationDecisionType.Allowed).ToString();
            }
            catch (Exception ex)
            {
                dict["ex"]    = ex.ToString();
                dict["error"] = ex.Message;
            }

            return(dict);
        }
Пример #4
0
        // snippet-end:[STS.dotnetv3.AssumeRoleAsync]

        // snippet-start:[IAM.dotnetv3.DeleteResourcesAsync]

        /// <summary>
        /// Delete the user, and other resources created for this example.
        /// </summary>
        /// <param name="client">The initialized client object.</param>
        /// <param name=accessKeyId">The Id of the user's access key.</param>"
        /// <param name="userName">The user name of the user to delete.</param>
        /// <param name="policyName">The name of the policy to delete.</param>
        /// <param name="policyArn">The Amazon Resource Name ARN of the Policy to delete.</param>
        /// <param name="roleName">The name of the role that will be deleted.</param>
        public static async Task DeleteResourcesAsync(
            AmazonIdentityManagementServiceClient client,
            string accessKeyId,
            string userName,
            string policyArn,
            string roleName)
        {
            var detachPolicyResponse = await client.DetachRolePolicyAsync(new DetachRolePolicyRequest
            {
                PolicyArn = policyArn,
                RoleName  = roleName,
            });

            var delPolicyResponse = await client.DeletePolicyAsync(new DeletePolicyRequest
            {
                PolicyArn = policyArn,
            });

            var delRoleResponse = await client.DeleteRoleAsync(new DeleteRoleRequest
            {
                RoleName = roleName,
            });

            var delAccessKey = await client.DeleteAccessKeyAsync(new DeleteAccessKeyRequest
            {
                AccessKeyId = accessKeyId,
                UserName    = userName,
            });

            var delUserResponse = await client.DeleteUserAsync(new DeleteUserRequest
            {
                UserName = userName,
            });
        }
Пример #5
0
        /// <summary>
        /// Internal method that cleans up the created user pool (along with associated client/user)
        /// for testing
        /// </summary>
        public override void Dispose()
        {
            try
            {
                using (var client = new AmazonIdentityManagementServiceClient())
                {
                    client.DetachRolePolicyAsync(new DetachRolePolicyRequest()
                    {
                        PolicyArn = policyArn,
                        RoleName  = roleName
                    }).Wait();

                    client.DeletePolicyAsync(new DeletePolicyRequest()
                    {
                        PolicyArn = policyArn
                    }).Wait();

                    client.DeleteRoleAsync(new DeleteRoleRequest()
                    {
                        RoleName = roleName
                    }).Wait();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            base.Dispose();
        }
Пример #6
0
        public CreateDeploymentResponse DeployToStack(
            AmazonCodeDeployClient codeDeployClient,
            AmazonIdentityManagementServiceClient iamClient,
            AmazonAutoScalingClient autoScalingClient,
            Role role)
        {
            var deploymentGroupName = _stackName + "_" + BundleName;

            EnsureDeploymentGroupExistsForBundle(codeDeployClient, iamClient, autoScalingClient, role, deploymentGroupName);

            var deploymentResponse = codeDeployClient.CreateDeployment(new CreateDeploymentRequest
            {
                ApplicationName     = CodeDeployApplicationName,
                DeploymentGroupName = deploymentGroupName,
                Revision            = new RevisionLocation
                {
                    RevisionType = RevisionLocationType.S3,
                    S3Location   = new S3Location
                    {
                        Bucket     = Bucket,
                        Key        = FileName,
                        BundleType = BundleType.Zip,
                        ETag       = ETag
                    }
                }
            });

            return(deploymentResponse);
        }
Пример #7
0
        /// <summary>
        /// Create the role if it's not there already.
        /// Return true if it already existed.
        /// </summary>
        /// <returns></returns>
        private static async Task <bool> ValidateAndSetIamRoleArn(AmazonIdentityManagementServiceClient iamClient)
        {
            var getRoleRequest = new GetRoleRequest
            {
                RoleName = ExecutionRoleName
            };

            try
            {
                ExecutionRoleArn = (await iamClient.GetRoleAsync(getRoleRequest)).Role.Arn;
                return(true);
            }
            catch (NoSuchEntityException)
            {
                // create the role
                var createRoleRequest = new CreateRoleRequest
                {
                    RoleName    = ExecutionRoleName,
                    Description = "Test role for CustomRuntimeTests.",
                    AssumeRolePolicyDocument = LAMBDA_ASSUME_ROLE_POLICY
                };
                ExecutionRoleArn = (await iamClient.CreateRoleAsync(createRoleRequest)).Role.Arn;

                // Wait for role to propagate.
                await Task.Delay(10000);

                return(false);
            }
        }
Пример #8
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);
        }
Пример #9
0
        /// <summary>
        /// Initializes an IAM Client object and then calls CreatePolicyAsync
        /// to create the policy.
        /// </summary>
        public static async Task Main()
        {
            // Represents JSON code for AWS managed full access policy for
            // Amazon Simple Storage Service (Amazon S3).
            string s3FullAccessPolicy = "{" +
                                        "	\"Statement\" : [{"+
                                        "	\"Action\" : [\"s3:*\"],"+
                                        "	\"Effect\" : \"Allow\","+
                                        "	\"Resource\" : \"*\""+
                                        "}]" +
                                        "}";

            string policyName = "S3FullAccess";

            var client   = new AmazonIdentityManagementServiceClient();
            var response = await client.CreatePolicyAsync(new CreatePolicyRequest
            {
                PolicyDocument = s3FullAccessPolicy,
                PolicyName     = policyName,
            });

            if (response is not null)
            {
                var policy = response.Policy;
                Console.WriteLine($"{policy.PolicyName} created with ID: {policy.PolicyId}.");
            }
            else
            {
                Console.WriteLine("Coultn't create policy.");
            }
        }
        public async Task TestThreadingLogging()
        {
            // run all test cases in one test to ensure they run serially
            using (var lambdaClient = new AmazonLambdaClient(TestRegion))
                using (var s3Client = new AmazonS3Client(TestRegion))
                    using (var iamClient = new AmazonIdentityManagementServiceClient(TestRegion))
                    {
                        var roleAlreadyExisted = false;

                        try
                        {
                            roleAlreadyExisted = await PrepareTestResources(s3Client, lambdaClient, iamClient);
                            await InvokeLoggerTestController(lambdaClient);
                        }
                        catch (NoDeploymentPackageFoundException)
                        {
#if DEBUG
                            // The CodePipeline for this project doesn't currently build the deployment in the stage that runs
                            // this test. For now ignore this test in release mode if the deployment package can't be found.
                            throw;
#endif
                        }
                        finally
                        {
                            await CleanUpTestResources(s3Client, lambdaClient, iamClient, roleAlreadyExisted);
                        }
                    }
        }
Пример #11
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);
        }
Пример #12
0
        /// <summary>
        /// Delete the instance profile created for the sample.
        /// </summary>
        void DeleteInstanceProfile()
        {
            var roleName = "magicec2" + RESOURCDE_POSTFIX;
            // AmazonIdentityManagementServiceClient
            var client = new AmazonIdentityManagementServiceClient(accessKeyId, secretAccessKey, region);

            client.DeleteRolePolicyAsync(new DeleteRolePolicyRequest
            {
                RoleName   = roleName,
                PolicyName = "S3Access"
            });

            client.RemoveRoleFromInstanceProfileAsync(new RemoveRoleFromInstanceProfileRequest
            {
                InstanceProfileName = roleName,
                RoleName            = roleName
            });

            client.DeleteRoleAsync(new DeleteRoleRequest
            {
                RoleName = roleName
            });

            client.DeleteInstanceProfileAsync(new DeleteInstanceProfileRequest
            {
                InstanceProfileName = roleName
            });
        }
Пример #13
0
        public void SetUp()
        {
            _awsConfiguration = new AwsConfiguration
            {
                AwsEndpoint = TestConfiguration.AwsEndpoint,
                Credentials = new TestSuiteCredentials()
            };

            _iamClient = new AmazonIdentityManagementServiceClient(
                new AmazonIdentityManagementServiceConfig
            {
                RegionEndpoint = _awsConfiguration.AwsEndpoint,
                ProxyHost      = _awsConfiguration.ProxyHost,
                ProxyPort      = _awsConfiguration.ProxyPort
            });

            var user = _iamClient.CreateUser(new CreateUserRequest
            {
                UserName = _userName
            }).User;

            _roleToAssume = _iamClient.CreateRoleToAssume(user);
            _awsConfiguration.RoleName = _roleToAssume.Arn;

            _s3Client = new AmazonS3Client(new AmazonS3Config {
                RegionEndpoint = _awsConfiguration.AwsEndpoint
            });

            DeletePreviousTestStack();
        }
Пример #14
0
        private static void UpdateAccessKey(String UAccessKeyId, String Status, String UserName = "")
        {
            if (String.IsNullOrEmpty(Token))
            {
                stsClient = new AmazonIdentityManagementServiceClient(AccessKeyId, SecretKey, iamconfig);
            }
            else
            {
                stsClient = new AmazonIdentityManagementServiceClient(AccessKeyId, SecretKey, Token, iamconfig);
            }

            UpdateAccessKeyRequest req = new UpdateAccessKeyRequest(UAccessKeyId, Status);

            if (!String.IsNullOrEmpty(UserName))
            {
                req.UserName = UserName;
            }

            try
            {
                UpdateAccessKeyResponse response = stsClient.UpdateAccessKey(req);
                Console.WriteLine("User updated");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occured while creating user. " + ex.ToString());
            }
        }
Пример #15
0
        /// <summary>
        /// This method creates a new IAM user.
        /// </summary>
        /// <param name="client">The IAM client object.</param>
        /// <param name="request">The user creation request.</param>
        /// <returns>The object returned by the call to CreateUserAsync.</returns>
        public static async Task <User> CreateNewUserAsync(AmazonIdentityManagementServiceClient client, CreateUserRequest request)
        {
            CreateUserResponse response = null;

            try
            {
                response = await client.CreateUserAsync(request);

                // Show the information about the user from the response.
                Console.WriteLine("\n--------------------------------------------------------------------------------------------------------------");
                Console.WriteLine($"New user: {response.User.UserName} ARN = {response.User.Arn}.");
                Console.WriteLine($"{response.User.UserName} has {response.User.PermissionsBoundary}.");
            }
            catch (EntityAlreadyExistsException ex)
            {
                Console.WriteLine($"{ex.Message}");
            }

            if (response is not null)
            {
                return(response.User);
            }
            else
            {
                return(null);
            }
        }
Пример #16
0
        public UpdateSAMLProviderResponse updateSAMLProvider(string accountId)
        {
            AmazonIdentityManagementServiceClient client = new AmazonIdentityManagementServiceClient();;

            if (accountId != "177654365656")
            {
                var credentials = AssumeIdentity.AssumeRole(accountId).Credentials;

                string accessKey    = credentials.AccessKeyId;
                string secretkey    = credentials.SecretAccessKey;
                string sessionToken = credentials.SessionToken;

                client = new AmazonIdentityManagementServiceClient(accessKey, secretkey, sessionToken);
            }

            UpdateSAMLProviderRequest request = new UpdateSAMLProviderRequest()
            {
                SAMLMetadataDocument = MetadataXML(),
                SAMLProviderArn      = string.Format("arn:aws:iam::{0}:saml-provider/ADFS", accountId)
            };

            UpdateSAMLProviderResponse response = client.UpdateSAMLProviderAsync(request).Result;

            return(response);
        }
Пример #17
0
        public static void CleanupTestRoleAndUser(string roleName, string userName)
        {
            using (var iamClient = new AmazonIdentityManagementServiceClient())
            {
                try
                {
                    var rolePolicies = iamClient.ListRolePolicies(new ListRolePoliciesRequest {
                        RoleName = roleName
                    }).PolicyNames;
                    foreach (var policy in rolePolicies)
                    {
                        iamClient.DeleteRolePolicy(new DeleteRolePolicyRequest
                        {
                            RoleName   = roleName,
                            PolicyName = policy
                        });
                    }
                    iamClient.DeleteRole(new DeleteRoleRequest {
                        RoleName = roleName
                    });
                }
                catch (NoSuchEntityException)
                {
                    //this is ok - only clean up if it exists
                }

                try
                {
                    var userPolicies = iamClient.ListUserPolicies(new ListUserPoliciesRequest {
                        UserName = userName
                    }).PolicyNames;
                    foreach (var policy in userPolicies)
                    {
                        iamClient.DeleteUserPolicy(new DeleteUserPolicyRequest
                        {
                            UserName   = userName,
                            PolicyName = policy
                        });
                    }
                    var accessKeys = iamClient.ListAccessKeys(new ListAccessKeysRequest {
                        UserName = userName
                    });
                    foreach (var accessKey in accessKeys.AccessKeyMetadata)
                    {
                        iamClient.DeleteAccessKey(new DeleteAccessKeyRequest
                        {
                            UserName    = userName,
                            AccessKeyId = accessKey.AccessKeyId
                        });
                    }
                    iamClient.DeleteUser(new DeleteUserRequest {
                        UserName = userName
                    });
                }
                catch (NoSuchEntityException)
                {
                    //this is ok - only clean up if it exists
                }
            }
        }
Пример #18
0
        static async Task <string> GetRoleArn(string roleName)
        {
            try
            {
                var config = new AmazonIdentityManagementServiceConfig();
                config.RegionEndpoint = region;
                using (var aimsc = new AmazonIdentityManagementServiceClient(config))
                {
                    var response = await aimsc.GetRoleAsync(new GetRoleRequest
                    {
                        RoleName = roleName
                    });

                    Role role = response.Role;
                    return(role.Arn);
                }
            }
            catch (NoSuchEntityException) // role was not present
            {
                return(null);
            }
            catch (AmazonIdentityManagementServiceException imsException)
            {
                Console.WriteLine(imsException.Message, imsException.InnerException);
                throw;
            }
        }
Пример #19
0
        /// <summary>
        /// Clean up all test resources.
        /// Also cleans up any resources that might be left from previous failed/interrupted tests.
        /// </summary>
        /// <param name="s3Client"></param>
        /// <param name="lambdaClient"></param>
        /// <returns></returns>
        private async Task CleanUpTestResources(AmazonS3Client s3Client, AmazonLambdaClient lambdaClient,
                                                AmazonIdentityManagementServiceClient iamClient, bool roleAlreadyExisted)
        {
            await DeleteFunctionIfExistsAsync(lambdaClient);

            var listBucketsResponse = await s3Client.ListBucketsAsync();

            foreach (var bucket in listBucketsResponse.Buckets)
            {
                if (bucket.BucketName.StartsWith(TestBucketRoot))
                {
                    await DeleteDeploymentZipAndBucketAsync(s3Client, bucket.BucketName);
                }
            }

            if (!roleAlreadyExisted)
            {
                try
                {
                    var deleteRoleRequest = new DeleteRoleRequest
                    {
                        RoleName = ExecutionRoleName
                    };
                    await iamClient.DeleteRoleAsync(deleteRoleRequest);
                }
                catch (Exception)
                {
                    // no problem - it's best effort
                }
            }
        }
Пример #20
0
        public JObject FunctionHandler(JObject input)
        {
            JObject createAccountResponseObject = JObject.FromObject(input.SelectToken("CreateAccountResponse"));
            string  accountId = createAccountResponseObject.SelectToken("CreateAccountStatus.AccountId").ToString();

            var credentials = AssumeIdentity.AssumeRole(accountId).Credentials;

            string accessKey    = credentials.AccessKeyId;
            string secretkey    = credentials.SecretAccessKey;
            string sessionToken = credentials.SessionToken;

            AmazonIdentityManagementServiceClient client = new AmazonIdentityManagementServiceClient(accessKey, secretkey, sessionToken);

            AttachRolePolicyRequest request = new AttachRolePolicyRequest()
            {
                PolicyArn = "arn:aws:iam::aws:policy/AdministratorAccess",
                RoleName  = input.SelectToken("EventData.roleName").ToString()
            };

            AttachRolePolicyResponse response = client.AttachRolePolicyAsync(request).Result;

            JObject outputObject = new JObject();

            outputObject.Add("AttachRolePolicyResponse", JObject.FromObject(response));
            outputObject.Add("CreateAccountResponse", input.SelectToken("CreateAccountResponse"));
            outputObject.Add("EventData", input.SelectToken("EventData"));

            return(outputObject);
        }
Пример #21
0
        public async Task TestAllHandlersAsync()
        {
            // run all test cases in one test to ensure they run serially
            using (var lambdaClient = new AmazonLambdaClient(TestRegion))
                using (var s3Client = new AmazonS3Client(TestRegion))
                    using (var iamClient = new AmazonIdentityManagementServiceClient(TestRegion))
                    {
                        var roleAlreadyExisted = false;

                        try
                        {
                            roleAlreadyExisted = await PrepareTestResources(s3Client, lambdaClient, iamClient);

                            await RunTestSuccessAsync(lambdaClient, "ToUpperAsync", "message", "ToUpperAsync-MESSAGE");
                            await RunTestSuccessAsync(lambdaClient, "PingAsync", "ping", "PingAsync-pong");
                            await RunTestSuccessAsync(lambdaClient, "HttpsWorksAsync", "", "HttpsWorksAsync-SUCCESS");
                            await RunTestSuccessAsync(lambdaClient, "CertificateCallbackWorksAsync", "", "CertificateCallbackWorksAsync-SUCCESS");
                            await RunTestSuccessAsync(lambdaClient, "NetworkingProtocolsAsync", "", "NetworkingProtocolsAsync-SUCCESS");
                            await RunTestSuccessAsync(lambdaClient, "HandlerEnvVarAsync", "", "HandlerEnvVarAsync-HandlerEnvVarAsync");
                            await RunTestExceptionAsync(lambdaClient, "AggregateExceptionUnwrappedAsync", "", "Exception", "Exception thrown from an async handler.");
                            await RunTestExceptionAsync(lambdaClient, "AggregateExceptionUnwrapped", "", "Exception", "Exception thrown from a synchronous handler.");
                            await RunTestExceptionAsync(lambdaClient, "AggregateExceptionNotUnwrappedAsync", "", "AggregateException", "AggregateException thrown from an async handler.");
                            await RunTestExceptionAsync(lambdaClient, "AggregateExceptionNotUnwrapped", "", "AggregateException", "AggregateException thrown from a synchronous handler.");
                            await RunTestExceptionAsync(lambdaClient, "TooLargeResponseBodyAsync", "", "Function.ResponseSizeTooLarge", "Response payload size (7340060 bytes) exceeded maximum allowed payload size (6291556 bytes).");
                            await RunTestSuccessAsync(lambdaClient, "LambdaEnvironmentAsync", "", "LambdaEnvironmentAsync-SUCCESS");
                            await RunTestSuccessAsync(lambdaClient, "LambdaContextBasicAsync", "", "LambdaContextBasicAsync-SUCCESS");
                            await RunTestSuccessAsync(lambdaClient, "GetPidDllImportAsync", "", "GetPidDllImportAsync-SUCCESS");
                            await RunTestSuccessAsync(lambdaClient, "GetTimezoneNameAsync", "", "GetTimezoneNameAsync-UTC");
                        }
                        finally
                        {
                            await CleanUpTestResources(s3Client, lambdaClient, iamClient, roleAlreadyExisted);
                        }
                    }
        }
Пример #22
0
        public static async Task Main()
        {
            var iamClient = new AmazonIdentityManagementServiceClient();
            var s3Client  = new AmazonS3Client();

            // Clear the console screen before displaying any text.
            Console.Clear();

            // Create an IAM group.
            var createGroupResponse = await CreateNewGroupAsync(iamClient, GroupName);

            // Create a policy and add it to the group.
            var success = await AddGroupPermissionsAsync(iamClient, createGroupResponse.Group);

            // Now create a new user.
            User readOnlyUser;
            var  userRequest = new CreateUserRequest
            {
                UserName = UserName,
            };

            readOnlyUser = await CreateNewUserAsync(iamClient, userRequest);

            // Create access and secret keys for the user.
            CreateAccessKeyResponse createKeyResponse = await CreateNewAccessKeyAsync(iamClient, UserName);

            // Add the new user to the group.
            success = await AddNewUserToGroupAsync(iamClient, readOnlyUser.UserName, createGroupResponse.Group.GroupName);

            // Show that the user can access Amazon S3 by listing the buckets on
            // the account.
            Console.Write("Waiting for user status to be Active.");
            do
            {
                Console.Write(" .");
            }while (createKeyResponse.AccessKey.Status != StatusType.Active);

            await ListBucketsAsync(createKeyResponse.AccessKey);

            // Show that the user also has write access to Amazon S3 by creating
            // a new bucket.
            success = await CreateS3BucketAsync(createKeyResponse.AccessKey, BucketName);

            if (success)
            {
                Console.WriteLine($"Successfully created the bucket: {BucketName}.");
            }

            // Delete the user, the group, and the new bucket.
            await CleanUpResources(
                iamClient,
                s3Client,
                UserName,
                GroupName,
                BucketName,
                createKeyResponse.AccessKey.AccessKeyId);

            Console.WriteLine("Press <Enter> to close the program.");
            Console.ReadLine();
        }
Пример #23
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonIdentityManagementServiceConfig config = new AmazonIdentityManagementServiceConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonIdentityManagementServiceClient client = new AmazonIdentityManagementServiceClient(creds, config);


            ListRolesResponse resp = new ListRolesResponse();

            do
            {
                ListRolesRequest req = new ListRolesRequest
                {
                    Marker = resp.Marker
                    ,
                    MaxItems = maxItems
                };

                resp = client.ListRoles(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.Roles)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.Marker));
        }
Пример #24
0
        public async Task <VerificationResult> VerifyContent()
        {
            VerificationResult verificationResult = new VerificationResult();

            Credentials credentials = new Credentials();

            credentials.SecretAccessKey = secretAccessKeyTextBox.Text;
            credentials.AccessKeyId     = accessKeyIdTextBox.Text;

            AmazonIdentityManagementServiceClient client = new AmazonIdentityManagementServiceClient(credentials.AccessKeyId, credentials.SecretAccessKey, Amazon.RegionEndpoint.EUWest2);

            try
            {
                GetUserResponse response = await client.GetUserAsync();

                verificationResult.IsVerified = string.IsNullOrEmpty(response.User?.UserName);

                if (verificationResult.IsVerified)
                {
                    NewVerifiedCredentials?.Invoke(this, credentials);
                }
                else
                {
                    verificationResult.ErrorMessage = "Failed to verify credentials";
                }
            }
            catch
            {
                verificationResult.IsVerified   = false;
                verificationResult.ErrorMessage = "Failed to verify credentials";
            }

            return(verificationResult);
        }
Пример #25
0
        public static void AttachRolePolicy()
        {
            var               client      = new AmazonIdentityManagementServiceClient();
            string            policy      = GenerateRolePolicyDocument();
            CreateRoleRequest roleRequest = new CreateRoleRequest()
            {
                RoleName = "tester",
                AssumeRolePolicyDocument = policy
            };

            var request = new AttachRolePolicyRequest()
            {
                PolicyArn = "arn:aws:iam::123456789:policy/DemoEC2Permissions",
                RoleName  = "tester"
            };

            try
            {
                var response = client.AttachRolePolicy(request);
                Console.WriteLine("Policy DemoEC2Permissions attached to Role TestUser");
            }
            catch (NoSuchEntityException)
            {
                Console.WriteLine
                    ("Policy 'DemoEC2Permissions' does not exist");
            }
            catch (InvalidInputException)
            {
                Console.WriteLine
                    ("One of the parameters is incorrect");
            }
        }
Пример #26
0
        public JObject FunctionHandler(JObject input)
        {
            LambdaLogger.Log(JObject.FromObject(input).ToString());
            string accountId = input.SelectToken("CreateAccountStatus.CreateAccountStatus.AccountId").ToString();

            var credentials = AssumeIdentity.AssumeRole(accountId).Credentials;

            string accessKey    = credentials.AccessKeyId;
            string secretkey    = credentials.SecretAccessKey;
            string sessionToken = credentials.SessionToken;

            AmazonIdentityManagementServiceClient client = new AmazonIdentityManagementServiceClient(accessKey, secretkey, sessionToken);

            CreateSAMLProviderRequest request = new CreateSAMLProviderRequest()
            {
                Name = "ADFS",
                SAMLMetadataDocument = MetadataXML()
            };

            CreateSAMLProviderResponse response = client.CreateSAMLProviderAsync(request).Result;

            JObject outputObject = new JObject();

            outputObject.Add("CreateSAMLProviderResponse", JObject.FromObject(response));
            outputObject.Add("CreateAccountResponse", input.SelectToken("CreateAccountStatus"));
            outputObject.Add("EventData", input.SelectToken("EventData"));

            return(outputObject);
        }
Пример #27
0
        public static User CreateReadOnlyUser()
        {
            var iamClient = new AmazonIdentityManagementServiceClient();

            try
            {
                // Create the IAM user
                var readOnlyUser = iamClient.CreateUser(new CreateUserRequest
                {
                    UserName = "******"
                }).User;

                // Assign the read only policy to the new user
                iamClient.PutUserPolicy(new PutUserPolicyRequest
                {
                    UserName       = readOnlyUser.UserName,
                    PolicyName     = "S3ReadOnlyAccess",
                    PolicyDocument = S3_READONLY_POLICY
                });
                return(readOnlyUser);
            }
            catch (EntityAlreadyExistsException e)
            {
                Console.WriteLine(e.Message);
                var request = new GetUserRequest()
                {
                    UserName = "******"
                };

                return(iamClient.GetUser(request).User);
            }
        }
        public JObject FunctionHandler(JObject input)
        {
            JObject createAccountResponseObject = JObject.FromObject(input.SelectToken("CreateAccountResponse"));
            string  accountId = createAccountResponseObject.SelectToken("CreateAccountStatus.AccountId").ToString();

            var credentials = AssumeIdentity.AssumeRole(accountId).Credentials;

            string accessKey    = credentials.AccessKeyId;
            string secretkey    = credentials.SecretAccessKey;
            string sessionToken = credentials.SessionToken;

            AmazonIdentityManagementServiceClient client = new AmazonIdentityManagementServiceClient(accessKey, secretkey, sessionToken);

            CreateRoleRequest request = new CreateRoleRequest()
            {
                RoleName                 = input.SelectToken("EventData.roleName").ToString(),
                MaxSessionDuration       = 43200,
                AssumeRolePolicyDocument = "{ \"Version\": \"2012-10-17\", \"Statement\": { \"Effect\": \"Allow\", \"Action\": \"sts:AssumeRoleWithSAML\", \"Principal\": {\"Federated\": \"arn:aws:iam::" + accountId + ":saml-provider/ADFS\"}, \"Condition\": {\"StringEquals\": {\"SAML:aud\": \"https://signin.aws.amazon.com/saml\"}} } }"
            };

            CreateRoleResponse response = client.CreateRoleAsync(request).Result;

            JObject outputObject = new JObject();

            outputObject.Add("CreateAccountResponse", createAccountResponseObject);
            outputObject.Add("CreateRoleResponse", JObject.FromObject(response));
            outputObject.Add("EventData", input.SelectToken("EventData"));

            return(outputObject);
        }
Пример #29
0
        private Dictionary <string, string> CreateUnprivilegedUser(string awsid, string awskey, string path)
        {
            var now        = Library.Utility.Utility.SerializeDateTime(DateTime.Now);
            var username   = string.Format("duplicati-autocreated-backup-user-{0}", now);
            var policyname = string.Format("duplicati-autocreated-policy-{0}", now);
            var policydoc  = GeneratePolicyDoc(path);

            var cl   = new AmazonIdentityManagementServiceClient(awsid, awskey);
            var user = cl.CreateUser(new CreateUserRequest(username)).User;

            cl.PutUserPolicy(new PutUserPolicyRequest(
                                 user.UserName,
                                 policyname,
                                 policydoc
                                 ));
            var key = cl.CreateAccessKey(new CreateAccessKeyRequest()
            {
                UserName = user.UserName
            }).AccessKey;

            var dict = new Dictionary <string, string>();

            dict["accessid"]  = key.AccessKeyId;
            dict["secretkey"] = key.SecretAccessKey;
            dict["username"]  = key.UserName;

            return(dict);
        }
Пример #30
0
        private static void ListSamlProviders()
        {
            if (String.IsNullOrEmpty(Token))
            {
                stsClient = new AmazonIdentityManagementServiceClient(AccessKeyId, SecretKey, iamconfig);
            }
            else
            {
                stsClient = new AmazonIdentityManagementServiceClient(AccessKeyId, SecretKey, Token, iamconfig);
            }

            ListSAMLProvidersRequest req = new ListSAMLProvidersRequest();

            try
            {
                ListSAMLProvidersResponse response = stsClient.ListSAMLProviders(req);
                foreach (SAMLProviderListEntry entry in response.SAMLProviderList)
                {
                    Console.WriteLine("ARN: {0}, Valid Until: {1}, Create Date: {2}", entry.Arn, entry.ValidUntil, entry.CreateDate);
                }
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occured while creating user. " + ex.ToString());
            }
        }