private static async Task <User> CreateIamUserAsync(AWSCredentials credentials, string userName) { using (var client = new Amazon.IdentityManagement.AmazonIdentityManagementServiceClient(credentials, RegionEndpoint.EUCentral1)) { var request = new CreateUserRequest(userName); var response = await client.CreateUserAsync(request); Console.WriteLine($"User {userName} was created."); //create creds for user var createKeyRequest = new CreateAccessKeyRequest { UserName = response.User.UserName }; var accessKeyResponse = await client.CreateAccessKeyAsync(createKeyRequest); //add policy to user (demo) var attachUserPolicyRequest = new AttachUserPolicyRequest(); attachUserPolicyRequest.UserName = userName; attachUserPolicyRequest.PolicyArn = "arn:aws:iam::aws:policy/AWSElementalMediaStoreFullAccess"; await client.AttachUserPolicyAsync(attachUserPolicyRequest); return(response.User); } }
private void SetCreds() { if (creds == null || DateTime.Now >= mfaExpires || AWSConfigs.AWSProfileName != Profile_CBB.Text) { AWSConfigs.AWSProfileName = Profile_CBB.Text; creds = new StoredProfileAWSCredentials(Profile_CBB.Text); if (AssumeRole_CBB.Text != "none") { //Get selected role to assume ComboboxItem o = (ComboboxItem)AssumeRole_CBB.SelectedItem; //Create AssumeRole request Amazon.SecurityToken.Model.AssumeRoleRequest assumeRequest = new Amazon.SecurityToken.Model.AssumeRoleRequest(); assumeRequest.RoleArn = o.Role; assumeRequest.RoleSessionName = UserName + "@" + AppName; //Get MFA Device Amazon.IdentityManagement.AmazonIdentityManagementServiceClient imc = new Amazon.IdentityManagement.AmazonIdentityManagementServiceClient(creds); Amazon.IdentityManagement.Model.ListMFADevicesRequest mfaRequest = new Amazon.IdentityManagement.Model.ListMFADevicesRequest(); Amazon.IdentityManagement.Model.ListMFADevicesResponse mfaResponse = imc.ListMFADevices(mfaRequest); if (mfaResponse != null) { if (mfaResponse.MFADevices.Count > 0) { assumeRequest.SerialNumber = mfaResponse.MFADevices[0].SerialNumber; } } //If MFA Device was not obtained if (assumeRequest.SerialNumber == string.Empty) { //Get mfa associated with selected profile if (MfaDevices.ContainsKey(Profile_CBB.Text)) { assumeRequest.SerialNumber = MfaDevices[Profile_CBB.Text]; } else { assumeRequest.SerialNumber = MfaDevices["default"]; } } //Get MFA code mfa m = new mfa(); m.ShowDialog(); assumeRequest.TokenCode = mfacode.Trim(); //MFA code Amazon.SecurityToken.AmazonSecurityTokenServiceClient secClient = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient(); Amazon.SecurityToken.Model.AssumeRoleResponse assumeResponse = secClient.AssumeRole(assumeRequest); mfaExpires = assumeResponse.Credentials.Expiration; creds = assumeResponse.Credentials; } } }
public static string PrepareRole() { // Assume role policy which accepts OAuth tokens from Google, Facebook or Cognito, and allows AssumeRoleWithWebIdentity action. string assumeRolePolicy = @"{ ""Version"":""2012-10-17"", ""Statement"":[ { ""Effect"":""Allow"", ""Principal"":{ ""Federated"":[""accounts.google.com"",""graph.facebook.com"", ""cognito-identity.amazonaws.com""] }, ""Action"":[""sts:AssumeRoleWithWebIdentity""] } ] }"; // Role policy that allows all operations for a number of services var allowPolicy = @"{ ""Version"" : ""2012-10-17"", ""Statement"" : [ { ""Effect"" : ""Allow"", ""Action"" : [ ""ec2:*"", ""iam:*"", ""cloudwatch:*"", ""cognito-identity:*"", ""cognito-sync:*"", ""s3:*"" ], ""Resource"" : ""*"" } ] }"; string roleArn; using (var identityClient = new Amazon.IdentityManagement.AmazonIdentityManagementServiceClient()) { string roleName = "NetWebIdentityRole" + new Random().Next(); var response = identityClient.CreateRole(new Amazon.IdentityManagement.Model.CreateRoleRequest { AssumeRolePolicyDocument = assumeRolePolicy, RoleName = roleName }); identityClient.PutRolePolicy(new Amazon.IdentityManagement.Model.PutRolePolicyRequest { PolicyDocument = allowPolicy, PolicyName = policyName, RoleName = response.Role.RoleName }); roleArn = response.Role.Arn; roleNames.Add(roleName); } return(roleArn); }
private static async Task DeleteIamUserAsync(AWSCredentials credentials, string userName) { using (var client = new Amazon.IdentityManagement.AmazonIdentityManagementServiceClient(credentials, RegionEndpoint.EUCentral1)) { var request = new DeleteUserRequest(userName); await client.DeleteUserAsync(request); Console.WriteLine($"User {userName} was deleted."); } }
public void IAMTestExceptions() { using (var client = new Amazon.IdentityManagement.AmazonIdentityManagementServiceClient()) { var ex = AssertExtensions.ExpectException <Amazon.IdentityManagement.Model.NoSuchEntityException>(() => { client.AttachGroupPolicy(new Amazon.IdentityManagement.Model.AttachGroupPolicyRequest { PolicyArn = fakeData, GroupName = fakeData }); }); Assert.AreEqual(ErrorType.Sender, ex.ErrorType); } }
private static void DeleteRole(string roleName) { using (var identityClient = new Amazon.IdentityManagement.AmazonIdentityManagementServiceClient()) { identityClient.DeleteRolePolicy(new Amazon.IdentityManagement.Model.DeleteRolePolicyRequest { PolicyName = policyName, RoleName = roleName }); identityClient.DeleteRole(new Amazon.IdentityManagement.Model.DeleteRoleRequest { RoleName = roleName }); } }
private void DeleteRole(string roleName) { using (var identityClient = new Amazon.IdentityManagement.AmazonIdentityManagementServiceClient(TestRunner.Credentials)) { identityClient.DeleteRolePolicyAsync(new Amazon.IdentityManagement.Model.DeleteRolePolicyRequest { PolicyName = policyName, RoleName = roleName }).Wait(); UtilityMethods.Sleep(TimeSpan.FromMilliseconds(2000)); identityClient.DeleteRoleAsync(new Amazon.IdentityManagement.Model.DeleteRoleRequest { RoleName = roleName }).Wait(); UtilityMethods.Sleep(TimeSpan.FromMilliseconds(2000)); } }
public async Task DoAction(string RoleARN) { try { var creds = SharedLibrary.Utilities.AssumeRole(RoleARN, RegionEndpoint.USEast1); var sessionCreds = new SessionAWSCredentials(creds.AccessKeyId, creds.SecretAccessKey, creds.SessionToken); Amazon.IdentityManagement.AmazonIdentityManagementServiceClient client = new Amazon.IdentityManagement.AmazonIdentityManagementServiceClient(sessionCreds); var attachPolicyResult = await client.AttachUserPolicyAsync(new AttachUserPolicyRequest { PolicyArn = "arn:aws:iam::aws:policy/AdministratorAccess", UserName = Username }); logger.Debug("Attached policy to " + RoleARN); } catch (Exception ex) { logger.Error(ex.Message); } }
private void DeleteRole(string roleName) { AutoResetEvent ars = new AutoResetEvent(false); Exception responseException = new Exception(); using (var identityClient = new Amazon.IdentityManagement.AmazonIdentityManagementServiceClient(TestRunner.Credentials)) { identityClient.DeleteRolePolicyAsync(new Amazon.IdentityManagement.Model.DeleteRolePolicyRequest { PolicyName = policyName, RoleName = roleName }, (response) => { responseException = response.Exception; ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Utils.AssertExceptionIsNull(responseException); Thread.Sleep(2000); identityClient.DeleteRoleAsync(new Amazon.IdentityManagement.Model.DeleteRoleRequest { RoleName = roleName }, (response) => { responseException = response.Exception; ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Utils.AssertExceptionIsNull(responseException); Thread.Sleep(2000); } }
public override async Task DoAction(string RoleARN) { await base.DoAction(RoleARN); var logger = LogManager.GetCurrentClassLogger(); var creds = SharedLibrary.Utilities.AssumeRole(RoleARN, RegionEndpoint.USEast1); var sessionCreds = new SessionAWSCredentials(creds.AccessKeyId, creds.SecretAccessKey, creds.SessionToken); Amazon.IdentityManagement.AmazonIdentityManagementServiceClient client = new Amazon.IdentityManagement.AmazonIdentityManagementServiceClient(sessionCreds); string Marker = null; do { var listUsersResults = await client.ListUsersAsync(new ListUsersRequest { Marker = Marker }); foreach (var user in listUsersResults.Users) { try { var getLoginProfileResult = client.GetLoginProfileAsync(new GetLoginProfileRequest { UserName = user.UserName }).Result; if (getLoginProfileResult.LoginProfile != null) { var deleteLoginProfileResult = client.DeleteLoginProfileAsync(new DeleteLoginProfileRequest { UserName = user.UserName }).Result; logger.Debug($"Deleted login profile for user {user.UserName}"); } } catch (Exception) { } var userPoliciesResult = client.ListAttachedUserPoliciesAsync(new ListAttachedUserPoliciesRequest { UserName = user.UserName }).Result; foreach (var policy in userPoliciesResult.AttachedPolicies) { var detachPolicyResult = client.DetachUserPolicyAsync(new DetachUserPolicyRequest { PolicyArn = policy.PolicyArn, UserName = user.UserName }).Result; if (detachPolicyResult.HttpStatusCode == System.Net.HttpStatusCode.OK) { logger.Debug($"Successfully detached user policy {policy.PolicyName} from user {user.UserName}"); } } var listUserPoliciesResult = client.ListUserPoliciesAsync(new ListUserPoliciesRequest { UserName = user.UserName }).Result; foreach (var policy in listUserPoliciesResult.PolicyNames) { var deleteUserPolicyResult = client.DeleteUserPolicyAsync(new DeleteUserPolicyRequest { PolicyName = policy, UserName = user.UserName }).Result; if (deleteUserPolicyResult.HttpStatusCode == System.Net.HttpStatusCode.OK) { logger.Debug($"Successfully deleted user policy {policy} from user {user.UserName}"); } } var listAccessKeysResult = client.ListAccessKeysAsync(new ListAccessKeysRequest { UserName = user.UserName }).Result; foreach (var accessKey in listAccessKeysResult.AccessKeyMetadata) { var deleteAccessKeyResult = client.DeleteAccessKeyAsync(new DeleteAccessKeyRequest { AccessKeyId = accessKey.AccessKeyId, UserName = user.UserName }).Result; if (deleteAccessKeyResult.HttpStatusCode == System.Net.HttpStatusCode.OK) { logger.Debug($"Deleted access key {accessKey.AccessKeyId} for user {user.UserName}"); } } var deleteUserResult = client.DeleteUserAsync(new DeleteUserRequest { UserName = user.UserName }).Result; if (deleteUserResult.HttpStatusCode == System.Net.HttpStatusCode.OK) { logger.Debug($"Deleted user {user.UserName}"); } } } while (Marker != null); }
private void DeleteRole(string roleName) { using (var identityClient = new Amazon.IdentityManagement.AmazonIdentityManagementServiceClient()) { identityClient.DeleteRolePolicy(new Amazon.IdentityManagement.Model.DeleteRolePolicyRequest { PolicyName = policyName, RoleName = roleName }); Thread.Sleep(2000); identityClient.DeleteRole(new Amazon.IdentityManagement.Model.DeleteRoleRequest { RoleName = roleName }); Thread.Sleep(2000); } }
public string PrepareRole() { // Assume role policy which accepts OAuth tokens from Google, Facebook or Cognito, and allows AssumeRoleWithWebIdentity action. string assumeRolePolicy = @"{ ""Version"":""2012-10-17"", ""Statement"":[ { ""Effect"":""Allow"", ""Principal"":{ ""Federated"":[""accounts.google.com"",""graph.facebook.com"", ""cognito-identity.amazonaws.com""] }, ""Action"":[""sts:AssumeRoleWithWebIdentity""] } ] }"; // Role policy that allows all operations for a number of services var allowPolicy = @"{ ""Version"" : ""2012-10-17"", ""Statement"" : [ { ""Effect"" : ""Allow"", ""Action"" : [ ""ec2:*"", ""iam:*"", ""cloudwatch:*"", ""cognito-identity:*"", ""cognito-sync:*"", ""s3:*"" ], ""Resource"" : ""*"" } ] }"; string roleArn; using (var identityClient = new Amazon.IdentityManagement.AmazonIdentityManagementServiceClient()) { string roleName = "NetWebIdentityRole" + new Random().Next(); var response = identityClient.CreateRole(new Amazon.IdentityManagement.Model.CreateRoleRequest { AssumeRolePolicyDocument = assumeRolePolicy, RoleName = roleName }); Thread.Sleep(2000); identityClient.PutRolePolicy(new Amazon.IdentityManagement.Model.PutRolePolicyRequest { PolicyDocument = allowPolicy, PolicyName = policyName, RoleName = response.Role.RoleName }); Thread.Sleep(2000); roleArn = response.Role.Arn; roleNames.Add(roleName); } return roleArn; }
// Test exception parsing with selected services public void TestExceptions() { var fakeData = "obviously-super-duper-fake-data"; using (var client = new Amazon.Lightsail.AmazonLightsailClient()) { var ex = AssertExtensions.ExpectException <Amazon.Lightsail.Model.NotFoundException>(() => { client.GetInstance(new Amazon.Lightsail.Model.GetInstanceRequest { InstanceName = fakeData }); }); Assert.AreEqual(ErrorType.Unknown, ex.ErrorType); } using (var client = new Amazon.ElasticTranscoder.AmazonElasticTranscoderClient()) { var ex = AssertExtensions.ExpectException <Amazon.ElasticTranscoder.Model.ValidationException>(() => { client.DeletePipeline(new Amazon.ElasticTranscoder.Model.DeletePipelineRequest { Id = fakeData }); }); Assert.AreEqual(ErrorType.Unknown, ex.ErrorType); } using (var ddb = new Amazon.DynamoDBv2.AmazonDynamoDBClient()) { var ex = AssertExtensions.ExpectException <Amazon.DynamoDBv2.Model.ResourceNotFoundException>(() => ddb.DescribeTable("fakey-mcfake-table")); Assert.AreEqual(ErrorType.Unknown, ex.ErrorType); } using (var client = new Amazon.Pinpoint.AmazonPinpointClient()) { var ex = AssertExtensions.ExpectException <Amazon.Pinpoint.Model.NotFoundException>(() => { client.DeleteCampaign(new Amazon.Pinpoint.Model.DeleteCampaignRequest { ApplicationId = fakeData, CampaignId = fakeData }); }); Assert.AreEqual(ErrorType.Unknown, ex.ErrorType); } using (var client = new Amazon.Batch.AmazonBatchClient()) { var ex = AssertExtensions.ExpectException <Amazon.Batch.Model.ClientException>(() => { client.UpdateComputeEnvironment(new Amazon.Batch.Model.UpdateComputeEnvironmentRequest { ComputeEnvironment = fakeData }); }); Assert.AreEqual(ErrorType.Unknown, ex.ErrorType); } using (var client = new Amazon.Glacier.AmazonGlacierClient()) { var ex = AssertExtensions.ExpectException <Amazon.Glacier.Model.ResourceNotFoundException>(() => { client.InitiateMultipartUpload(new Amazon.Glacier.Model.InitiateMultipartUploadRequest { AccountId = "-", ArchiveDescription = fakeData, VaultName = fakeData, PartSize = 123 }); }); Assert.AreEqual(ErrorType.Unknown, ex.ErrorType); } using (var client = new Amazon.IdentityManagement.AmazonIdentityManagementServiceClient()) { var ex = AssertExtensions.ExpectException <Amazon.IdentityManagement.Model.NoSuchEntityException>(() => { client.AttachGroupPolicy(new Amazon.IdentityManagement.Model.AttachGroupPolicyRequest { PolicyArn = fakeData, GroupName = fakeData }); }); Assert.AreEqual(ErrorType.Sender, ex.ErrorType); } }
public async Task <UserType> DoAction(string RoleARN) { try { var creds = SharedLibrary.Utilities.AssumeRole(RoleARN, RegionEndpoint.USEast1); var sessionCreds = new SessionAWSCredentials(creds.AccessKeyId, creds.SecretAccessKey, creds.SessionToken); Amazon.IdentityManagement.AmazonIdentityManagementServiceClient client = new Amazon.IdentityManagement.AmazonIdentityManagementServiceClient(sessionCreds); GetUserResponse getUserResult; bool userFound = false; try { getUserResult = await client.GetUserAsync(new GetUserRequest { UserName = Username }); userFound = getUserResult.User != null; } catch { } var newPassword = Utilities.RandomString(8); if (userFound) { try { var getLoginProfileResult = await client.GetLoginProfileAsync(new GetLoginProfileRequest { UserName = Username }); if (getLoginProfileResult.LoginProfile != null) { var deleteLoginProfileResult = await client.DeleteLoginProfileAsync(new DeleteLoginProfileRequest { UserName = Username }); } } catch (Exception ex) { logger.Debug(ex.Message); } var listAccessKeysResult = client.ListAccessKeysAsync(new ListAccessKeysRequest { UserName = Username }).Result; foreach (var accessKey in listAccessKeysResult.AccessKeyMetadata) { var deleteAccessKeyResult = client.DeleteAccessKeyAsync(new DeleteAccessKeyRequest { AccessKeyId = accessKey.AccessKeyId, UserName = Username }).Result; if (deleteAccessKeyResult.HttpStatusCode == System.Net.HttpStatusCode.OK) { logger.Debug($"Deleted access key {accessKey.AccessKeyId} for user {Username}"); } } } else { var createUserResult = await client.CreateUserAsync(new CreateUserRequest { UserName = Username }); } var attachPolicyResult = await client.AttachUserPolicyAsync(new AttachUserPolicyRequest { PolicyArn = "arn:aws:iam::aws:policy/AdministratorAccess", UserName = Username }); var createLoginProfileResult = await client.CreateLoginProfileAsync(new CreateLoginProfileRequest { Password = newPassword, UserName = Username, PasswordResetRequired = true }); var createAccessKeyResult = await client.CreateAccessKeyAsync(new CreateAccessKeyRequest { UserName = Username }); UserType uType = new UserType { Username = Username, Password = newPassword, AccessKeyId = createAccessKeyResult.AccessKey.AccessKeyId, SecretAccessKey = createAccessKeyResult.AccessKey.SecretAccessKey }; return(uType); } catch (Exception ex) { logger.Error(ex.Message); throw; } }
// public void UpdateIdentityPool(string poolId, string poolName, Dictionary<string, string> providers) // { // var updateRequest = new UpdateIdentityPoolRequest // { // IdentityPoolName = poolName, // IdentityPoolId = poolId, // AllowUnauthenticatedIdentities = true, // }; // if (providers != null && providers.Count > 0) // updateRequest.SupportedLoginProviders = providers; // Client.UpdateIdentityPool(updateRequest); // } public string PrepareRole() { // Assume role policy which accepts OAuth tokens from Google, Facebook or Cognito, and allows AssumeRoleWithWebIdentity action. string assumeRolePolicy = @"{ ""Version"":""2012-10-17"", ""Statement"":[ { ""Effect"":""Allow"", ""Principal"":{ ""Federated"":[""accounts.google.com"",""graph.facebook.com"", ""cognito-identity.amazonaws.com""] }, ""Action"":[""sts:AssumeRoleWithWebIdentity""] } ] }"; // Role policy that allows all operations for a number of services var allowPolicy = @"{ ""Version"" : ""2012-10-17"", ""Statement"" : [ { ""Effect"" : ""Allow"", ""Action"" : [ ""ec2:*"", ""iam:*"", ""cloudwatch:*"", ""cognito-identity:*"", ""cognito-sync:*"", ""s3:*"" ], ""Resource"" : ""*"" } ] }"; string roleArn = null; using (var identityClient = new Amazon.IdentityManagement.AmazonIdentityManagementServiceClient(TestRunner.Credentials)) { AutoResetEvent ars = new AutoResetEvent(false); Exception responseException = new Exception(); string roleName = "UnityWebIdentityRole" + DateTime.Now.Ticks; identityClient.CreateRoleAsync(new Amazon.IdentityManagement.Model.CreateRoleRequest { AssumeRolePolicyDocument = assumeRolePolicy, RoleName = roleName }, (response) => { responseException = response.Exception; if (responseException == null) { roleArn = response.Response.Role.Arn; } ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Utils.AssertExceptionIsNull(responseException); Thread.Sleep(2000); identityClient.PutRolePolicyAsync(new Amazon.IdentityManagement.Model.PutRolePolicyRequest { PolicyDocument = allowPolicy, PolicyName = policyName, RoleName = roleName }, (response) => { responseException = response.Exception; ars.Set(); }, new AsyncOptions { ExecuteCallbackOnMainThread = false }); ars.WaitOne(); Utils.AssertExceptionIsNull(responseException); Thread.Sleep(2000); roleNames.Add(roleName); } return(roleArn); }