Implementation for accessing AmazonIdentityManagementService. AWS Identity and Access Management

AWS Identity and Access Management (IAM) is a web service that you can use to manage users and user permissions under your AWS account. This guide provides descriptions of the IAM API. For general information about IAM, see AWS Identity and Access Management (IAM) . For the user guide for IAM, see Using IAM .

NOTE: AWS provides SDKs that consist of libraries and sample code for various programming languages and platforms (Java, Ruby, .NET, iOS, Android, etc.). The SDKs provide a convenient way to create programmatic access to IAM and AWS. For example, the SDKs take care of tasks such as cryptographically signing requests (see below), managing errors, and retrying requests automatically. For information about the AWS SDKs, including how to download and install them, see the Tools for Amazon Web Services page.

Using the IAM Query API, you make direct calls to the IAM web service. IAM supports GET and POST requests for all actions. That is, the API does not require you to use GET for some actions and POST for others. However, GET requests are subject to the limitation size of a URL; although this limit is browser dependent, a typical limit is 2048 bytes. Therefore, for operations that require larger sizes, you must use a POST request.

Signing Requests Requests must be signed using an access key ID and a secret access key. We strongly recommend that you do not use your AWS account access key ID and secret access key for everyday work with IAM. You can use the access key ID and secret access key for an IAM user or you can use the AWS Security Token Service to generate temporary security credentials and use those to sign requests.

To sign requests, we recommend that you use Signature Version 4 . If you have an existing application that uses Signature Version 2, you do not have to update it to use Signature Version 4. However, some operations now require Signature Version 4. The documentation for operations that require version 4 indicate this requirement.

Additional Resources For more information, see the following:

  • AWS Security Credentials . This topic provides general information about the types of credentials used for accessing AWS.
  • IAM Best Practices . This topic presents a list of suggestions for using the IAM service to help secure your AWS resources.
  • AWS Security Token Service . This guide describes how to create and use temporary security credentials.
  • Signing AWS API Requests . This set of topics walk you through the process of signing a request using an access key ID and secret access key.
Inheritance: AmazonWebServiceClient, IAmazonIdentityManagementService
 public void CheckWeAreRunningAsTheSpecialUser()
 {
     ConfigurationManager.AppSettings["AWSProfileName"] = "aws-tools-tests";
     var iamClient = new AmazonIdentityManagementServiceClient();
     var me = iamClient.GetUser();
     Assert.That(me.User.UserName, Is.EqualTo("aws-tools-tests"));
 }
        public void EnsureStackExists()
        {
            if (_hasCreatedStack) return;

            _awsConfiguration = new AwsConfiguration
            {
                AssumeRoleTrustDocument = Roles.Path("code-deploy-trust.json"),
                IamRolePolicyDocument = Roles.Path("code-deploy-policy.json"),
                Bucket = "aws-deployment-tools-tests",
                RoleName = "CodeDeployRole",
                AwsEndpoint = TestConfiguration.AwsEndpoint,
                Credentials = new TestSuiteCredentials()
            };

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

            DeletePreviousTestStack();

            _deployer = new Deployer(_awsConfiguration);

            _stack = _deployer.CreateStack(new StackTemplate
            {
                StackName = StackName,
                TemplatePath = CloudFormationTemplates.Path("example-windows-vpc-autoscaling-group.template")
            });
            _hasCreatedStack = true;
        }
示例#3
0
 public static void DeleteAccessKeysForUser(AmazonIdentityManagementServiceClient client, string username)
 {
     ListAccessKeysResponse response = client.ListAccessKeys(new ListAccessKeysRequest() { UserName = username });
     foreach (AccessKeyMetadata akm in response.AccessKeyMetadata)
     {
         client.DeleteAccessKey(new DeleteAccessKeyRequest() { UserName = username, AccessKeyId = akm.AccessKeyId });
     }
 }
示例#4
0
 public static void DeleteUserPoliciesForUser(AmazonIdentityManagementServiceClient client, string username)
 {
     ListUserPoliciesResponse response =
         client.ListUserPolicies(new ListUserPoliciesRequest() { UserName = username });
     foreach (string pName in response.PolicyNames)
     {
         client.DeleteUserPolicy(new DeleteUserPolicyRequest() { UserName = username, PolicyName = pName });
     }
 }
示例#5
0
 public static void DeleteCertificatesForUser(AmazonIdentityManagementServiceClient client, string username)
 {
     ListSigningCertificatesResponse response =
         client.ListSigningCertificates(new ListSigningCertificatesRequest() { UserName = username });
     foreach (SigningCertificate cert in response.Certificates)
     {
         client.DeleteSigningCertificate(new DeleteSigningCertificateRequest() { UserName = username, CertificateId = cert.CertificateId });
     }
 }
示例#6
0
        public static void SetSecurityTokenServicePrefs(Credentials creds)
        {
            Amazon.IdentityManagement.AmazonIdentityManagementServiceClient client = new Amazon.IdentityManagement.AmazonIdentityManagementServiceClient(creds);

            var setResult = client.SetSecurityTokenServicePreferencesAsync(new Amazon.IdentityManagement.Model.SetSecurityTokenServicePreferencesRequest {
                GlobalEndpointTokenVersion = GlobalEndpointTokenVersion.V2Token
            }).Result;

            if (setResult.HttpStatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception();
            }
        }
示例#7
0
 public static void DeleteTestUsers(AmazonIdentityManagementServiceClient client, params string[] usernames)
 {
     foreach (string s in usernames)
     {
         DeleteAccessKeysForUser(client, s);
         DeleteUserPoliciesForUser(client, s);
         DeleteCertificatesForUser(client, s);
         try 
         {
             client.DeleteLoginProfile(new DeleteLoginProfileRequest() { UserName = s }); 
         } catch { /* Nobody cares */ }
         client.DeleteUser(new DeleteUserRequest() { UserName = s });
     }
 }
示例#8
0
        private static void AddPolicy()
        {
            var client = new AmazonIdentityManagementServiceClient();
            var policyRequest = new PutUserPolicyRequest
            {
                UserName = "******",
                PolicyName = "EC2Policy",
                PolicyDocument =
                    "{\"Version\": \"2012-10-17\",\"Statement\": [ {\"Sid\": \"Stmt1453760589829\",\"Action\": [\"ec2:DescribeInstances\"],\"Effect\": \"Allow\",\"Resource\":\"*\"}]}"
            };

            var policyResponse = client.PutUserPolicy(policyRequest);
            Console.WriteLine("Policy Added");
        }
示例#9
0
        private static void CreateUser()
        {
            Console.WriteLine("** Create User **");
            var iamClient = new AmazonIdentityManagementServiceClient();
            var request = new CreateUserRequest
            {
                UserName = "******",
                Path = @"/IT/architecture/"
            };

            var response = iamClient.CreateUser(request);

            Console.WriteLine("User Created");

        }
        /// <summary>
        /// Uploads the Server Cert
        /// </summary>
        /// <param name="certNameWithDateTime"></param>
        /// <param name="iam"></param>
        /// <returns></returns>
        private async Task<UploadServerCertificateResponse> UploadServerCertificateAsync(string certNameWithDateTime, AmazonIdentityManagementServiceClient iam)
        {
            loggerProvider.GetLogger().Debug($"Uploading ssl. [Name: {configurationProvider.CertName}]");

            var certChain = await GetCertificateChainForCertAsync();

            var uploadRequest = new UploadServerCertificateRequest
            {
                ServerCertificateName = certNameWithDateTime,
                CertificateBody = configurationProvider.CertBody,
                PrivateKey = configurationProvider.CertPrivateKey,
                CertificateChain = certChain
            };
            var uploadResult = await iam.UploadServerCertificateAsync(uploadRequest);
            return uploadResult;
        }
示例#11
0
        public static void DeleteTestUsers(AmazonIdentityManagementServiceClient client, params string[] usernames)
        {
            UtilityMethods.WaitUntilSuccess(() => {
                foreach (string s in usernames)
                {
                    DeleteAccessKeysForUser(client, s);
                    DeleteUserPoliciesForUser(client, s);
                    DeleteCertificatesForUser(client, s);
                    try 
                    {
                        client.DeleteLoginProfileAsync(new DeleteLoginProfileRequest() { UserName = s }).Wait(); 
                    } catch { }

                    client.DeleteUserAsync(new DeleteUserRequest() { UserName = s }).Wait();
                }
            });
        }
示例#12
0
        public static void DeleteUsersAndGroupsInTestNameSpace(AmazonIdentityManagementServiceClient client)
        {
            ListGroupsResponse lgRes = client.ListGroups(new ListGroupsRequest() { PathPrefix = TEST_PATH });
            foreach (Group g in lgRes.Groups)
            {
                GetGroupResponse ggRes = client.GetGroup(new GetGroupRequest() { GroupName = g.GroupName });
                foreach (User u in ggRes.Users)
                {
                    client.RemoveUserFromGroup(new RemoveUserFromGroupRequest() { GroupName = g.GroupName, UserName = u.UserName });
                }
                client.DeleteGroup(new DeleteGroupRequest() { GroupName = g.GroupName });
            }

            ListUsersResponse luRes = client.ListUsers(new ListUsersRequest() { PathPrefix = TEST_PATH });
            foreach (User u in luRes.Users)
            {
                DeleteTestUsers(client, u.UserName);
            }
        }
        public static IEnumerable<ServerCertificateMetadata> GetServerCertificates(AwsCommonParams commonParams)
        {
            using (var client = new AmazonIdentityManagementServiceClient(
                commonParams.ResolveCredentials(),
                commonParams.RegionEndpoint))
            {
                var iamRequ = new ListServerCertificatesRequest();

                do
                {
                    var iamResp = client.ListServerCertificates(iamRequ);
                    foreach (var r in iamResp.ServerCertificateMetadataList)
                        yield return r;

                    iamRequ.Marker = iamResp.Marker;
                    if (!iamResp.IsTruncated)
                        iamRequ = null;
                } while (iamRequ != null);
            }
        }
        public async Task<string> GetSslCertArnPathAsync()
        {
            if(string.IsNullOrWhiteSpace(configurationProvider.CertName))
            {
                loggerProvider.GetLogger().Debug("There is no cert name. Unable to lookup Arn Path.");
                return string.Empty;
            }

            if(string.IsNullOrWhiteSpace(configurationProvider.CertBody))
            {
                string msg = "CertBody is null or whitespace which is invalid.";
                loggerProvider.GetLogger().Warning(msg);
                throw new SslUploaderServiceException(msg);
            }

            loggerProvider.GetLogger().Debug($"Looking up SSL Cert ARN Path. [CertName: {configurationProvider.CertName}]");
            using (var iam = new AmazonIdentityManagementServiceClient(credentials))
            {
                var certExpireDateTime =  await GetCertExpireDateTime();

                var certNameWithDateTime = configurationProvider.CertName + certExpireDateTime.Ticks;

                loggerProvider.GetLogger().Debug($"Looking up Cert by Name. [LookupName: {certNameWithDateTime}]");
                var existingCert = await GetExistingCertByNameAsync(iam, certNameWithDateTime);

                if (existingCert != null)
                {
                    loggerProvider.GetLogger().Debug($"Ssl is already uploaded.  Returning ARN Path. [CertName: {configurationProvider.CertName}] [Arn: {existingCert.Arn}]");
                    return existingCert.Arn;
                }

                var uploadResult = await UploadServerCertificateAsync(certNameWithDateTime, iam);

                loggerProvider.GetLogger().Debug($"Cert uploaded successfully.  Returning ARN Path. [CertName: {configurationProvider.CertName}] [Arn: {uploadResult.ServerCertificateMetadata.Arn}]");
                return uploadResult.ServerCertificateMetadata.Arn;
            }
        }
示例#15
0
        public void SetUp()
        {
            var awsEndpoint = TestConfiguration.AwsEndpoint;
            var credentials = new TestSuiteCredentials();

            _s3Client = new AmazonS3Client(awsEndpoint);
            _iamClient = new AmazonIdentityManagementServiceClient(awsEndpoint);

            _awsConfiguration = new AwsConfiguration
            {
                IamRolePolicyDocument = Roles.Path("s3-policy-new-bucket.json"),
                AssumeRoleTrustDocument = Roles.Path("code-deploy-trust.json"),
                Bucket = "s3-push-test",
                RoleName = "SomeNewRole",
                AwsEndpoint = awsEndpoint,
                Credentials = credentials
            };

            _deployer = new Deployer(_awsConfiguration);
            _localBuildDirectory = ExampleRevisions.Directory("HelloWorld-1.2.3");
            _applicationSetName = "HelloWorld";
            _version = "1.1.1";
            DeleteRolesAndPolicies();
        }
        public void Uninstall(PrivateKey pk, Crt crt, IEnumerable<PKI.Crt> chain,
                IPkiTool cp)
        {
            AssertNotDisposed();

            using (var client = new AmazonIdentityManagementServiceClient(
                CommonParams.ResolveCredentials(),
                CommonParams.RegionEndpoint))
            {
                var iamRequ = new DeleteServerCertificateRequest
                {
                    ServerCertificateName = this.ServerCertificateName,
                };

                var iamResp = client.DeleteServerCertificate(iamRequ);
                // TODO:  any checks we should do?
            }
        }
示例#17
0
        public Deployer(AwsConfiguration awsConfiguration)
        {
            _awsEndpoint = awsConfiguration.AwsEndpoint;
            _bucket = awsConfiguration.Bucket;
            _assumeRoleTrustDocument = awsConfiguration.AssumeRoleTrustDocument;
            _iamRolePolicyDocument = awsConfiguration.IamRolePolicyDocument;

            AWSCredentials credentials;

            if (isArn(awsConfiguration.RoleName))
            {
                var securityTokenServiceClient = new AmazonSecurityTokenServiceClient(awsConfiguration.AwsEndpoint);

                var assumeRoleResult = securityTokenServiceClient.AssumeRole(new AssumeRoleRequest
                {
                    RoleArn = awsConfiguration.RoleName,
                    DurationSeconds = 3600,
                    RoleSessionName = "Net2User",
                    ExternalId = Guid.NewGuid().ToString()
                });

                Credentials stsCredentials = assumeRoleResult.Credentials;

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

                credentials = sessionCredentials;

                _role = new AssumedRole(assumeRoleResult.AssumedRoleUser);
            }
            else {
                credentials = awsConfiguration.Credentials ?? new EnvironmentAWSCredentials();
            }

            _codeDeployClient = new AmazonCodeDeployClient(
                credentials,
                new AmazonCodeDeployConfig {
                    RegionEndpoint = awsConfiguration.AwsEndpoint,
                    ProxyHost = awsConfiguration.ProxyHost,
                    ProxyPort = awsConfiguration.ProxyPort
                });

            _cloudFormationClient = new AmazonCloudFormationClient(
                credentials,
                new AmazonCloudFormationConfig {
                    RegionEndpoint = awsConfiguration.AwsEndpoint,
                    ProxyHost = awsConfiguration.ProxyHost,
                    ProxyPort = awsConfiguration.ProxyPort
                });

            _s3Client = new AmazonS3Client(
                credentials,
                new AmazonS3Config {
                    RegionEndpoint = awsConfiguration.AwsEndpoint,
                    ProxyHost = awsConfiguration.ProxyHost,
                    ProxyPort = awsConfiguration.ProxyPort
                });

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

            _autoScalingClient = new AmazonAutoScalingClient(
                credentials,
                new AmazonAutoScalingConfig {
                    RegionEndpoint = awsConfiguration.AwsEndpoint,
                    ProxyHost = awsConfiguration.ProxyHost,
                    ProxyPort = awsConfiguration.ProxyPort
                });
        }
 private async Task<bool> RoleAlreadyExistsAsync()
 {
     using (
         var iamClient = new AmazonIdentityManagementServiceClient(credentials,
             configurationProvider.RegionEndpoint))
     {
         var listRolesResponse = await iamClient.ListRolesAsync();
         return listRolesResponse.Roles
             .Any(r => string.Equals(r.RoleName, configurationProvider.ShortApplicationName,
                 StringComparison.CurrentCultureIgnoreCase));
     }
 }
        public async Task EnsureEc2ServiceRoleExistsAsync(string excuteApiUriForPolicy = "")
        {
            if (await RoleAlreadyExistsAsync())
            {
                loggerProvider.GetLogger()
                    .Debug("Role with roleName {roleName} already exists", configurationProvider.ShortApplicationName);
                return;
            }
            using (
                var iamClient = new AmazonIdentityManagementServiceClient(credentials,
                    configurationProvider.RegionEndpoint))
            {
                var createRoleResponse = await iamClient.CreateRoleAsync(new CreateRoleRequest
                {
                    RoleName = configurationProvider.ShortApplicationName,
                    AssumeRolePolicyDocument =
                        "{\"Version\": \"2012-10-17\", \"Statement\": {\"Effect\": \"Allow\", \"Principal\": { \"Service\": \"ec2.amazonaws.com\"}, \"Action\": \"sts:AssumeRole\"}}"
                });

                loggerProvider.GetLogger().Debug("The IAM Uri is " + excuteApiUriForPolicy);
                if (!string.IsNullOrWhiteSpace(excuteApiUriForPolicy))
                {
                    var policyDocument =
                   "{\"Version\": \"2012-10-17\", \"Statement\": [{\"Effect\": \"Allow\",\"Action\": [\"execute-api:Invoke\"],\"Resource\": \"arn:aws:execute-api:*:*:" +
                   excuteApiUriForPolicy + "\"}]}";

                    loggerProvider.GetLogger().Debug("The new Policy Reads : " + policyDocument);
                    var newPolicy = await iamClient.CreatePolicyAsync(new CreatePolicyRequest
                    {
                        Description =
                            "Policy to demonstrate that I have permission that is limited to a specific resource in ApiGateway ",
                        PolicyDocument = policyDocument,
                        PolicyName = "ResourceInvocation"
                    });

                    loggerProvider.GetLogger().Debug("Policy Created: " + newPolicy.Policy.Arn);
                    await iamClient.AttachRolePolicyAsync(new AttachRolePolicyRequest
                    {
                        RoleName = configurationProvider.ShortApplicationName,
                        PolicyArn = newPolicy.Policy.Arn
                    });
                    loggerProvider.GetLogger().Debug("Policy Attach to Role: " + newPolicy.Policy.Arn);
                }
                

                loggerProvider.GetLogger().Debug("Created role: {@createRoleResponse}", createRoleResponse);
                var createInstanceProfileResponse = iamClient.CreateInstanceProfile(new CreateInstanceProfileRequest
                {
                    InstanceProfileName = configurationProvider.ShortApplicationName
                });
                loggerProvider.GetLogger()
                    .Debug("Created instance profile: {@createInstanceProfileResponse}", createInstanceProfileResponse);
                var addRoleToInstanceProfileResponse =
                    iamClient.AddRoleToInstanceProfile(new AddRoleToInstanceProfileRequest
                    {
                        InstanceProfileName = configurationProvider.ShortApplicationName,
                        RoleName = configurationProvider.ShortApplicationName
                    });
                loggerProvider.GetLogger()
                    .Debug("Added role to instance profile: {@addRoleToInstanceProfileResponse}",
                        addRoleToInstanceProfileResponse);
            }
        }
示例#20
0
        public List<string> GetGroups(string aprofile)
        {
            List<string> ToReturn = new List<string>();
            Amazon.Runtime.AWSCredentials credential;
            try
            {
                string accountid = GetAccountID(aprofile);
                credential = new Amazon.Runtime.StoredProfileAWSCredentials(aprofile);
                var iam = new AmazonIdentityManagementServiceClient(credential);
                ListGroupsRequest req = new ListGroupsRequest();
                req.MaxItems = 100;
                
                var GROOPLIST = iam.ListGroups(req).Groups;
                foreach(var agroup in GROOPLIST)
                {
                    ToReturn.Add(agroup.GroupName);
                }
            }
            catch(Exception ex)
            {

            }



                return ToReturn;

        }
示例#21
0
        void EnsureDeploymentGroupExistsForBundle(AmazonCodeDeployClient codeDeployClient, AmazonIdentityManagementServiceClient iamClient, AmazonAutoScalingClient autoScalingClient, Role role, string deploymentGroupName)
        {
            var serviceRoleArn = role.Arn;

            if (TargetsAutoScalingDeploymentGroup)
            {
                var group =
                    autoScalingClient.DescribeAutoScalingGroups()
                        .AutoScalingGroups.FirstOrDefault(
                            asg => asg.Tags.Any(t => t.Key == "DeploymentRole" && t.Value == deploymentGroupName));

                if (group == null)
                    throw new ApplicationException(
                        string.Format("Auto scaling group with DeploymentRole {0} does not exist.", deploymentGroupName));

                try
                {
                    codeDeployClient.CreateDeploymentGroup(new CreateDeploymentGroupRequest
                    {
                        ApplicationName = CodeDeployApplicationName,
                        DeploymentGroupName = deploymentGroupName,
                        ServiceRoleArn = serviceRoleArn,
                        AutoScalingGroups = new List<string> {group.AutoScalingGroupName}
                    });
                }
                catch (DeploymentGroupAlreadyExistsException)
                {
                    // reuse a previously created deployment group with the same name
                }
            }
            else
            {
                try
                {
                    Console.WriteLine("Will assume role {0} for deployment", serviceRoleArn);
                    codeDeployClient.CreateDeploymentGroup(new CreateDeploymentGroupRequest
                    {
                        ApplicationName = CodeDeployApplicationName,
                        DeploymentGroupName = deploymentGroupName,
                        ServiceRoleArn = serviceRoleArn,
                        Ec2TagFilters = new List<EC2TagFilter>
                    {
                        new EC2TagFilter
                        {
                            Type = EC2TagFilterType.KEY_AND_VALUE,
                            Key = "DeploymentRole",
                            Value = deploymentGroupName
                        }
                    }
                    });
                }
                catch (DeploymentGroupAlreadyExistsException)
                {
                    // since this is EC2, we can reuse a previously created deployment group with the same name
                }
            }
        }
示例#22
0
        public DataTable GetCertDetails(string aprofile)
        {
            string accountid = GetAccountID(aprofile);
            DataTable ToReturn = AWSTables.GetCertDetailsTable();
            Amazon.Runtime.AWSCredentials credential;
            RegionEndpoint Endpoint2scan = RegionEndpoint.USEast1;
            try
            {
                credential = new Amazon.Runtime.StoredProfileAWSCredentials(aprofile);
                var iam = new AmazonIdentityManagementServiceClient(credential);
                var cervix = iam.ListServerCertificates();


                //How to get certificate details????


                foreach (var acert in cervix.ServerCertificateMetadataList)
                {
                    DataRow disone = ToReturn.NewRow();
                    disone["AccountID"] = accountid;
                    disone["Profile"] = aprofile;
                    disone["CertName"] = acert.ServerCertificateName;

                    //Cert Details
                    //disone["Status"] = acert.;
                    //disone["InUse"] = acert.xxx;
                    //disone["DomainName"] = acert.xxx;
                    //disone["AdditionalNames"] = acert.xxx;
                    disone["Identifier"] = acert.ServerCertificateId;
                    //disone["SerialNumber"] = acert.xxx;
                    //disone["AssociatedResources"] = acert.xxx;
                    //disone["RequestedAt"] = acert.xxx;
                    //disone["IssuedAt"] = acert.xxx;
                    //disone["NotBefore"] = acert.xxx;
                    disone["NotAfter"] = acert.Expiration;
                    //disone["PublicKeyInfo"] = acert.xxx;
                    //disone["SignatureAlgorithm"] = acert.xxx;
                    disone["ARN"] = acert.Arn;
                    ToReturn.Rows.Add(disone);
                }

            }//End of the big Try
            catch (Exception ex)
            {
                //Whyfor did it fail?
                string w = "";
            }

            return ToReturn;
        }
        public virtual void PrepMode_RemoveRoles(AmazonIdentityManagementServiceClient iamClient, params string[] roles)
        {
            foreach (var roleName in roles)
            {
                try
                {
                    iamClient.GetRole(new GetRoleRequest {RoleName = roleName});
                    Console.WriteLine("Removing old role {0}.", roleName);
                    // Remove existing policies
                    var listRolePoliciesResponse =
                        iamClient.ListRolePolicies(new ListRolePoliciesRequest {RoleName = roleName});
                    foreach (var policyName in listRolePoliciesResponse.PolicyNames)
                    {
                        var deleteRolePolicyRequest = new DeleteRolePolicyRequest
                        {
                            PolicyName = policyName,
                            RoleName = roleName
                        };
                        iamClient.DeleteRolePolicy(deleteRolePolicyRequest);
                    }
                    iamClient.DeleteRole(new DeleteRoleRequest {RoleName = roleName});
                }
                catch (NoSuchEntityException)
                {

                    // Role doesn't exist, so don't do anything.
                    // Gobble the exception and loop.
                    break;
                }
            }
        }
        public virtual string PrepMode_GetUserArn(AmazonIdentityManagementServiceClient iamClient, string userName)
        {
            var userArn = String.Empty;
            var getUserRequest = new GetUserRequest {UserName = userName};
            // Send the request and save the user arn.
            userArn = iamClient.GetUser(getUserRequest).User.Arn;

            return userArn;
        }
        public virtual 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;
        }
 public virtual bool AppMode_TestIamAccess(RegionEndpoint regionEndpoint, SessionAWSCredentials credentials)
 {
     try
     {
         var iamClient = new AmazonIdentityManagementServiceClient(credentials, regionEndpoint);
         iamClient.ListUsers(new ListUsersRequest());
         return true;
     }
     catch
     {
         return false;
     }
 }
示例#27
0
        /// <summary>
        /// Just playing with this for now.
        /// </summary>
        /// <param name="aprofile"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public string CreateIAMAccount(string aprofile, string username, string password)
        {
            string IRReturning = "Yop";
            var credential = new Amazon.Runtime.StoredProfileAWSCredentials(aprofile);
            var iam = new AmazonIdentityManagementServiceClient(credential);

            CreateUserRequest request = new CreateUserRequest();
            request.UserName = username;

            var repo = iam.CreateUser(request);
            var det = repo.ResponseMetadata;

            CreateAccessKeyRequest KeyRequest = new CreateAccessKeyRequest();
            KeyRequest.UserName = username;




            return IRReturning;
        }
示例#28
0
 public static string CreateTestUser(AmazonIdentityManagementServiceClient client)
 {
     string username = "******" + DateTime.Now.Ticks;
     client.CreateUser(new CreateUserRequest() { UserName = username, Path = TEST_PATH });
     return username;
 }
示例#29
0
        }//EndIamUserScan

        /// <summary>
        /// Given a profile and user, collect additional information.
        /// </summary>
        /// <param name="aprofile">An AWS Profile name stored in Windows Credential Store</param>
        /// <param name="auser">The Name of a User</param>
        /// <returns>Dictionary containing keys for each type of data[AccessKeys], [Groups], [Policies]</returns>
        public Dictionary<string, string> GetUserDetails(string aprofile, string username)
        {
            var credential = new Amazon.Runtime.StoredProfileAWSCredentials(aprofile);
            var iam = new AmazonIdentityManagementServiceClient(credential);
            Dictionary<string, string> ToReturn = new Dictionary<string, string>();
            string policylist = "";
            string aklist = "";
            string groups = "";
            try
            {
                ListAccessKeysRequest LAKREQ = new ListAccessKeysRequest();
                LAKREQ.UserName = username;
                var LAKRES = iam.ListAccessKeys(LAKREQ);
                foreach (var blivet in LAKRES.AccessKeyMetadata)
                {
                    if (aklist.Length > 1) aklist += "\n";
                    aklist += blivet.AccessKeyId + "  :  " + blivet.Status;
                }
            }
            catch { aklist = ""; }

            try
            {
                ListAttachedUserPoliciesRequest LAUPREQ = new ListAttachedUserPoliciesRequest();
                LAUPREQ.UserName = username;
                var LAUPRES = iam.ListAttachedUserPolicies(LAUPREQ);
                foreach (var apol in LAUPRES.AttachedPolicies)
                {
                    if (policylist.Length > 1) policylist += "\n";
                    policylist += apol.PolicyName;
                }
            }
            catch { policylist = ""; }

            try
            {
                var groopsreq = new ListGroupsForUserRequest();
                groopsreq.UserName = username;
                var LG = iam.ListGroupsForUser(groopsreq);
                foreach (var agroup in LG.Groups)
                {
                    if (groups.Length > 1) groups += "\n";
                    groups += agroup.GroupName;
                }
            }
            catch { groups = ""; }

            ToReturn.Add("Groups", groups);
            ToReturn.Add("Policies", policylist);
            ToReturn.Add("AccessKeys", aklist);
            return ToReturn;
        }
        public void Install(PrivateKey pk, Crt crt, IEnumerable<PKI.Crt> chain,
                IPkiTool cp)
        {
            AssertNotDisposed();

            string pkPem;
            using (var ms = new MemoryStream())
            {
                cp.ExportPrivateKey(pk, EncodingFormat.PEM, ms);
                pkPem = Encoding.UTF8.GetString(ms.ToArray());
            }

            string crtPem;
            using (var ms = new MemoryStream())
            {
                cp.ExportCertificate(crt, EncodingFormat.PEM, ms);
                crtPem = Encoding.UTF8.GetString(ms.ToArray());
            }

            string chainPem = null;
            if (chain != null)
            {
                using (var ms = new MemoryStream())
                {
                    foreach (var c in chain)
                    {
                        cp.ExportCertificate(c, EncodingFormat.PEM, ms);
                    }
                    chainPem = Encoding.UTF8.GetString(ms.ToArray());
                }
            }

            using (var client = new AmazonIdentityManagementServiceClient(
                CommonParams.ResolveCredentials(),
                CommonParams.RegionEndpoint))
            {
                var iamRequ = new UploadServerCertificateRequest
                {
                    PrivateKey = pkPem,
                    CertificateBody = crtPem,
                    CertificateChain = chainPem,

                    ServerCertificateName = this.ServerCertificateName,
                    Path = this.Path
                };

                var iamResp = client.UploadServerCertificate(iamRequ);
                // TODO:  any checks we should do?
            }
        }
示例#31
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;
        }