com.amazonaws.services.identitymanagement.AmazonIdentityManagement Java Examples

The following examples show how to use com.amazonaws.services.identitymanagement.AmazonIdentityManagement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IAMUtils.java    From pacbot with Apache License 2.0 7 votes vote down vote up
/**
 * Gets the inline user policy.
 *
 * @param userName
 *            the user name
 * @param policyName
 *            the policy name
 * @param amazonIdentityManagement
 *            the amazon identity management
 * @return the inline user policy
 */
private static Policy getInlineUserPolicy(String userName, String policyName,
		AmazonIdentityManagement amazonIdentityManagement) {
	Policy policy = new Policy();
	try {
		GetUserPolicyRequest policyRequest = new GetUserPolicyRequest();
		policyRequest.setUserName(userName);
		policyRequest.setPolicyName(policyName);
		GetUserPolicyResult policyResult = amazonIdentityManagement.getUserPolicy(policyRequest);
		String policyAsString = policyResult.getPolicyDocument();

		policyAsString = java.net.URLDecoder.decode(policyAsString, "UTF-8");
		policy = Policy.fromJson(policyAsString);
	} catch (Exception e) {
		logger.error(e.getMessage());
	}

	return policy;
}
 
Example #2
Source File: GetPolicy.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final String USAGE =
            "To run this example, supply a policy arn\n" +
            "Ex: GetPolicy <policy-arn>\n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String policy_arn = args[0];

        final AmazonIdentityManagement iam =
            AmazonIdentityManagementClientBuilder.defaultClient();

        GetPolicyRequest request = new GetPolicyRequest()
            .withPolicyArn(policy_arn);

        GetPolicyResult response = iam.getPolicy(request);

        System.out.format("Successfully retrieved policy %s",
                response.getPolicy().getPolicyName());
    }
 
Example #3
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch IAM roles.
 *
 * @param temporaryCredentials the temporary credentials
 * @param accountId the accountId
 * @param accountName the account name
 * @return the map
 */
public static  Map<String,List<Role>>  fetchIAMRoles(BasicSessionCredentials temporaryCredentials,String accountId,String accountName) {

	AmazonIdentityManagement iamClient = AmazonIdentityManagementClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(InventoryConstants.REGION_US_WEST_2).build();
	List<Role> roles = new ArrayList<>();
	ListRolesResult rslt;
	String marker = null;
	do{
		rslt =  iamClient.listRoles(new ListRolesRequest().withMarker(marker));
		roles.addAll(rslt.getRoles());
		marker = rslt.getMarker();
	}while(marker!=null);

	log.debug(InventoryConstants.ACCOUNT + accountId +" Type : IAM Roles >> "+roles.size());
	Map<String,List<Role>> iamRoles = new HashMap<>();
	iamRoles.put(accountId+delimiter+accountName, roles);
	return iamRoles;
}
 
Example #4
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch IAM roles test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchIAMRolesTest() throws Exception {
    
    mockStatic(AmazonIdentityManagementClientBuilder.class);
    AmazonIdentityManagement iamClient = PowerMockito.mock(AmazonIdentityManagement.class);
    AmazonIdentityManagementClientBuilder amazonIdentityManagementClientBuilder = PowerMockito.mock(AmazonIdentityManagementClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonIdentityManagementClientBuilder.standard()).thenReturn(amazonIdentityManagementClientBuilder);
    when(amazonIdentityManagementClientBuilder.withCredentials(anyObject())).thenReturn(amazonIdentityManagementClientBuilder);
    when(amazonIdentityManagementClientBuilder.withRegion(anyString())).thenReturn(amazonIdentityManagementClientBuilder);
    when(amazonIdentityManagementClientBuilder.build()).thenReturn(iamClient);
    
    ListRolesResult listRolesResult = new ListRolesResult();
    List<Role> roles = new ArrayList<>();
    roles.add(new Role());
    listRolesResult.setRoles(roles);
    when(iamClient.listRoles(anyObject())).thenReturn(listRolesResult);
    assertThat(inventoryUtil.fetchIAMRoles(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"),"account","accountName").size(), is(1));
}
 
Example #5
Source File: UpdateTrustPolicy.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Override
protected Void run() throws Exception {
	final String roleName = this.step.getRoleName();
	final String policyFile = this.step.getPolicyFile();

	Preconditions.checkArgument(roleName != null && !roleName.isEmpty(), "roleName must not be null or empty");
	Preconditions.checkArgument(policyFile != null && !policyFile.isEmpty(), "policyFile must not be null or empty");

	AmazonIdentityManagement iamClient = AWSClientFactory.create(AmazonIdentityManagementClientBuilder.standard(), Execution.this.getContext());

	UpdateAssumeRolePolicyRequest request = new UpdateAssumeRolePolicyRequest();
	request.withRoleName(roleName);
	request.withPolicyDocument(Execution.this.getContext().get(FilePath.class).child(policyFile).readToString());
	iamClient.updateAssumeRolePolicy(request);

	Execution.this.getContext().get(TaskListener.class).getLogger().format("Updated trust policy of role %s %n", roleName);

	return null;
}
 
Example #6
Source File: SetAccountAliasStep.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Override
protected Void run() throws Exception {
	TaskListener listener = this.getContext().get(TaskListener.class);
	AmazonIdentityManagement iamClient = AWSClientFactory.create(AmazonIdentityManagementClientBuilder.standard(), Execution.this.getContext());

	listener.getLogger().format("Checking for account alias %s %n", this.name);
	ListAccountAliasesResult listResult = iamClient.listAccountAliases();

	// no or different alias set
	if (listResult.getAccountAliases() == null || listResult.getAccountAliases().isEmpty() || !listResult.getAccountAliases().contains(this.name)) {
		// Update alias
		iamClient.createAccountAlias(new CreateAccountAliasRequest().withAccountAlias(this.name));
		listener.getLogger().format("Created account alias %s %n", this.name);
	} else {
		// Nothing to do
		listener.getLogger().format("Account alias already set %s %n", this.name);
	}
	return null;
}
 
Example #7
Source File: CreateUser.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final String USAGE =
            "To run this example, supply a username\n" +
            "Ex: CreateUser <username>\n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String username = args[0];

        final AmazonIdentityManagement iam =
            AmazonIdentityManagementClientBuilder.defaultClient();

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

        CreateUserResult response = iam.createUser(request);

        System.out.println("Successfully created user: " +
                response.getUser().getUserName());
    }
 
Example #8
Source File: GetServerCertificate.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final String USAGE =
            "To run this example, supply a certificate name\n" +
            "Ex: GetServerCertificate <certificate-name>\n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String cert_name = args[0];

        final AmazonIdentityManagement iam =
            AmazonIdentityManagementClientBuilder.defaultClient();

        GetServerCertificateRequest request = new GetServerCertificateRequest()
                    .withServerCertificateName(cert_name);

        GetServerCertificateResult response = iam.getServerCertificate(request);

        System.out.format("Successfully retrieved certificate with body %s",
                response.getServerCertificate().getCertificateBody());
    }
 
Example #9
Source File: IAMUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the inline role policy.
 *
 * @param roleName
 *            the role name
 * @param policyName
 *            the policy name
 * @param amazonIdentityManagement
 *            the amazon identity management
 * @return the inline role policy
 */
private static Policy getInlineRolePolicy(String roleName, String policyName,
		AmazonIdentityManagement amazonIdentityManagement) {
	Policy policy = new Policy();
	try {
		GetRolePolicyRequest policyRequest = new GetRolePolicyRequest();
		policyRequest.setRoleName(roleName);
		policyRequest.setPolicyName(policyName);
		GetRolePolicyResult policyResult = amazonIdentityManagement.getRolePolicy(policyRequest);
		String policyAsString = policyResult.getPolicyDocument();

		policyAsString = java.net.URLDecoder.decode(policyAsString, "UTF-8");
		policy = Policy.fromJson(policyAsString);
	} catch (Exception e) {
		logger.error(e.getMessage());
	}

	return policy;
}
 
Example #10
Source File: DeleteServerCertificate.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final String USAGE =
            "To run this example, supply a certificate name\n" +
            "Ex: DeleteServerCertificate <certificate-name>\n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String cert_name = args[0];

        final AmazonIdentityManagement iam =
            AmazonIdentityManagementClientBuilder.defaultClient();

        DeleteServerCertificateRequest request =
            new DeleteServerCertificateRequest()
                .withServerCertificateName(cert_name);

        DeleteServerCertificateResult response =
            iam.deleteServerCertificate(request);

        System.out.println("Successfully deleted server certificate " +
                cert_name);
    }
 
Example #11
Source File: DetachRolePolicy.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final String USAGE =
            "To run this example, supply a role name and policy arn\n" +
            "Ex: DetachRolePolicy <role-name> <policy-arn>>\n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String role_name = args[0];
        String policy_arn = args[1];

        final AmazonIdentityManagement iam =
            AmazonIdentityManagementClientBuilder.defaultClient();

        DetachRolePolicyRequest request = new DetachRolePolicyRequest()
            .withRoleName(role_name)
            .withPolicyArn(policy_arn);

        DetachRolePolicyResult response = iam.detachRolePolicy(request);

        System.out.println("Successfully detached policy " + policy_arn +
                " from role " + role_name);
    }
 
Example #12
Source File: DeleteAccountAlias.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final String USAGE =
            "To run this example, supply an account alias\n" +
            "Ex: DeleteAccountAlias <account-alias>\n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String alias = args[0];

        final AmazonIdentityManagement iam =
            AmazonIdentityManagementClientBuilder.defaultClient();

        DeleteAccountAliasRequest request = new DeleteAccountAliasRequest()
            .withAccountAlias(alias);

        DeleteAccountAliasResult response = iam.deleteAccountAlias(request);

        System.out.println("Successfully deleted account alias " + alias);
    }
 
Example #13
Source File: CreateAccessKey.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final String USAGE =
            "To run this example, supply an IAM user\n" +
            "Ex: CreateAccessKey <user>\n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String user = args[0];

        final AmazonIdentityManagement iam =
            AmazonIdentityManagementClientBuilder.defaultClient();

        CreateAccessKeyRequest request = new CreateAccessKeyRequest()
            .withUserName(user);

        CreateAccessKeyResult response = iam.createAccessKey(request);

        System.out.println("Created access key: " + response.getAccessKey());
    }
 
Example #14
Source File: AccessKeyLastUsed.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final String USAGE =
            "To run this example, supply an access key id\n" +
            "Ex: AccessKeyLastUsed <access-key-id>\n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String access_id = args[0];

        final AmazonIdentityManagement iam =
            AmazonIdentityManagementClientBuilder.defaultClient();

        GetAccessKeyLastUsedRequest request = new GetAccessKeyLastUsedRequest()
            .withAccessKeyId(access_id);

        GetAccessKeyLastUsedResult response = iam.getAccessKeyLastUsed(request);

        System.out.println("Access key was last used at: " +
                response.getAccessKeyLastUsed().getLastUsedDate());
    }
 
Example #15
Source File: CreatePolicy.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final String USAGE =
            "To run this example, supply a policy name\n" +
            "Ex: CreatePolicy <policy-name>\n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String policy_name = args[0];

        final AmazonIdentityManagement iam =
            AmazonIdentityManagementClientBuilder.defaultClient();

        CreatePolicyRequest request = new CreatePolicyRequest()
            .withPolicyName(policy_name)
            .withPolicyDocument(POLICY_DOCUMENT);

        CreatePolicyResult response = iam.createPolicy(request);

        System.out.println("Successfully created policy: " +
                response.getPolicy().getPolicyName());
    }
 
Example #16
Source File: DeleteAccessKey.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final String USAGE =
            "To run this example, supply a username and access key id\n" +
            "Ex: DeleteAccessKey <username> <access-key-id>\n";

        if (args.length != 2) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String username = args[0];
        String access_key = args[1];

        final AmazonIdentityManagement iam =
            AmazonIdentityManagementClientBuilder.defaultClient();

        DeleteAccessKeyRequest request = new DeleteAccessKeyRequest()
            .withAccessKeyId(access_key)
            .withUserName(username);

        DeleteAccessKeyResult response = iam.deleteAccessKey(request);

        System.out.println("Successfully deleted access key " + access_key +
                " from user " + username);
    }
 
Example #17
Source File: ListUsers.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final AmazonIdentityManagement iam =
            AmazonIdentityManagementClientBuilder.defaultClient();

        boolean done = false;
        ListUsersRequest request = new ListUsersRequest();

        while(!done) {
            ListUsersResult response = iam.listUsers(request);

            for(User user : response.getUsers()) {
                System.out.format("Retrieved user %s", user.getUserName());
            }

            request.setMarker(response.getMarker());

            if(!response.getIsTruncated()) {
                done = true;
            }
        }
    }
 
Example #18
Source File: CreateAccountAlias.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        final String USAGE =
            "To run this example, supply an alias\n" +
            "Ex: CreateAccountAlias <alias>\n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String alias = args[0];

        final AmazonIdentityManagement iam =
            AmazonIdentityManagementClientBuilder.defaultClient();

        CreateAccountAliasRequest request = new CreateAccountAliasRequest()
            .withAccountAlias(alias);

        CreateAccountAliasResult response = iam.createAccountAlias(request);

        System.out.println("Successfully created account alias: " + alias);
    }
 
Example #19
Source File: AwsIamService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
/**
 * Validates role ARN and returns an Role object if valid
 *
 * @param iam                     AmazonIdentityManagement client
 * @param roleArn                 role ARN
 * @param validationResultBuilder builder for any errors encountered
 * @return Role if role ARN is valid otherwise null
 */
public Role getRole(AmazonIdentityManagement iam, String roleArn,
        ValidationResultBuilder validationResultBuilder) {
    Role role = null;
    if (roleArn != null && roleArn.contains("/")) {
        String roleName = roleArn.split("/", 2)[1];
        GetRoleRequest roleRequest = new GetRoleRequest().withRoleName(roleName);
        try {
            role = iam.getRole(roleRequest).getRole();
        } catch (NoSuchEntityException | ServiceFailureException e) {
            String msg = String.format("Role (%s) doesn't exist.", roleArn);
            LOGGER.debug(msg, e);
            validationResultBuilder.error(msg);
        }
    }
    return role;
}
 
Example #20
Source File: AwsIDBrokerObjectStorageValidator.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public ValidationResult validateObjectStorage(AmazonIdentityManagement iam,
        SpiFileSystem spiFileSystem,
        ValidationResultBuilder resultBuilder) {
    List<CloudFileSystemView> cloudFileSystems = spiFileSystem.getCloudFileSystems();
    for (CloudFileSystemView cloudFileSystemView : cloudFileSystems) {
        CloudS3View cloudFileSystem = (CloudS3View) cloudFileSystemView;
        String instanceProfileArn = cloudFileSystem.getInstanceProfile();
        InstanceProfile instanceProfile = awsIamService.getInstanceProfile(iam, instanceProfileArn,
                resultBuilder);
        if (instanceProfile != null) {
            CloudIdentityType cloudIdentityType = cloudFileSystem.getCloudIdentityType();
            if (CloudIdentityType.ID_BROKER.equals(cloudIdentityType)) {
                validateIDBroker(iam, instanceProfile, cloudFileSystem, resultBuilder);
            } else if (CloudIdentityType.LOG.equals(cloudIdentityType)) {
                validateLog(instanceProfile, cloudFileSystem, resultBuilder);
            }
        }
    }

    return resultBuilder.build();
}
 
Example #21
Source File: AwsObjectStorageConnector.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public ObjectStorageValidateResponse validateObjectStorage(ObjectStorageValidateRequest request) {
    AwsCredentialView awsCredentialView = new AwsCredentialView(request.getCredential());
    AmazonIdentityManagement iam = awsClient.createAmazonIdentityManagement(awsCredentialView);
    SpiFileSystem spiFileSystem = request.getSpiFileSystem();
    ValidationResultBuilder resultBuilder = new ValidationResultBuilder();
    ValidationResult validationResult = awsIDBrokerObjectStorageValidator.validateObjectStorage(
            iam, spiFileSystem, resultBuilder);
    ObjectStorageValidateResponse response;
    if (validationResult.hasError()) {
        response = ObjectStorageValidateResponse.builder()
                .withStatus(ResponseStatus.ERROR)
                .withError(validationResult.getFormattedErrors())
                .build();
    } else {
        response = ObjectStorageValidateResponse.builder()
                .withStatus(ResponseStatus.OK)
                .build();
    }
    return response;
}
 
Example #22
Source File: AwsIamService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
/**
 * Validates instance profile ARN and returns an InstanceProfile object if valid
 *
 * @param iam                     AmazonIdentityManagement client
 * @param instanceProfileArn      instance profile ARN
 * @param validationResultBuilder builder for any errors encountered
 * @return InstanceProfile if instance profile ARN is valid otherwise null
 */
public InstanceProfile getInstanceProfile(AmazonIdentityManagement iam, String instanceProfileArn,
        ValidationResultBuilder validationResultBuilder) {
    InstanceProfile instanceProfile = null;
    if (instanceProfileArn != null && instanceProfileArn.contains("/")) {
        String instanceProfileName = instanceProfileArn.split("/", 2)[1];
        GetInstanceProfileRequest instanceProfileRequest = new GetInstanceProfileRequest()
                .withInstanceProfileName(instanceProfileName);
        try {
            instanceProfile = iam.getInstanceProfile(instanceProfileRequest).getInstanceProfile();
        } catch (NoSuchEntityException | ServiceFailureException e) {
            String msg = String.format("Instance profile (%s) doesn't exist.", instanceProfileArn);
            LOGGER.error(msg, e);
            validationResultBuilder.error(msg);
        }
    }
    return instanceProfile;
}
 
Example #23
Source File: AwsPlatformResources.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private Set<CloudAccessConfig> getAccessConfigByRole(AmazonIdentityManagement client) {
    LOGGER.info("Get all Roles from Amazon");
    String queryFailedMessage = "Could not get roles from Amazon: ";
    try {
        boolean finished = false;
        String marker = null;
        List<Role> roles = new LinkedList<>();
        while (!finished) {
            ListRolesRequest listRolesRequest = new ListRolesRequest();
            listRolesRequest.setMaxItems(fetchMaxItems);
            if (isNotEmpty(marker)) {
                listRolesRequest.setMarker(marker);
            }
            LOGGER.debug("About to fetch roles...");
            ListRolesResult listRolesResult = client.listRoles(listRolesRequest);
            roles.addAll(listRolesResult.getRoles());
            if (listRolesResult.isTruncated()) {
                marker = listRolesResult.getMarker();
            } else {
                finished = true;
            }
        }
        return roles.stream().map(this::roleToCloudAccessConfig).collect(Collectors.toSet());
    } catch (AmazonServiceException ase) {
        if (ase.getStatusCode() == UNAUTHORIZED) {
            String policyMessage = "Could not get roles because the user does not have enough permission. ";
            LOGGER.error(policyMessage + ase.getMessage(), ase);
            throw new CloudUnauthorizedException(ase.getErrorMessage(), ase);
        } else {
            LOGGER.info(queryFailedMessage + ase.getMessage(), ase);
            throw new CloudConnectorException(ase.getMessage(), ase);
        }
    } catch (Exception e) {
        LOGGER.warn(queryFailedMessage + e.getMessage(), e);
        throw new CloudConnectorException(e.getMessage(), e);
    }
}
 
Example #24
Source File: AwsIDBrokerMappedRolePermissionValidator.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
/**
 * Validates the cloudFileSystem
 *
 * @param cloudFileSystem         cloud file system to evaluate
 * @param validationResultBuilder builder for any errors encountered
 */
public void validate(AmazonIdentityManagement iam, CloudS3View cloudFileSystem,
        ValidationResultBuilder validationResultBuilder) {
    AccountMappingBase accountMappings = cloudFileSystem.getAccountMapping();
    if (accountMappings != null) {
        SortedSet<String> roleArns = getRoleArnsForUsers(getUsers(), accountMappings.getUserMappings());
        LOGGER.info("Getting role from AWS, roleArns.size: {}, roleArns: {}", roleArns.size(), roleArns);
        Set<Role> roles = awsIamService.getValidRoles(iam, roleArns, validationResultBuilder);

        boolean s3guardEnabled = cloudFileSystem.getS3GuardDynamoTableName() != null;
        List<String> policyFileNames = getPolicyFileNames(s3guardEnabled);

        SortedSet<String> failedActions = new TreeSet<>();
        for (StorageLocationBase location : cloudFileSystem.getLocations()) {
            if (checkLocation(location)) {
                Map<String, String> replacements = getPolicyJsonReplacements(location, cloudFileSystem);
                List<Policy> policies = getPolicies(policyFileNames, replacements);
                for (Role role : roles) {
                    try {
                        List<EvaluationResult> evaluationResults = awsIamService.validateRolePolicies(iam,
                                role, policies);
                        failedActions.addAll(getFailedActions(role, evaluationResults));
                    } catch (AmazonIdentityManagementException e) {
                        // Only log the error and keep processing. Failed actions won't be added, but
                        // processing doesn't get stopped either. This can happen due to rate limiting.
                        LOGGER.error("Unable to validate role policies for role {} due to {}", role.getArn(),
                                e.getMessage(), e);
                    }
                }
            }
        }
        if (!failedActions.isEmpty()) {
            String errorMessage = String.format("The role(s) (%s) don't have the required permissions:%n%s",
                            String.join(", ", roles.stream().map(Role::getArn).collect(Collectors.toCollection(TreeSet::new))),
                            String.join("\n", failedActions));
            LOGGER.warn(errorMessage);
            validationResultBuilder.error(errorMessage);
        }
    }
}
 
Example #25
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch IAM certificate info.
 *
 * @param temporaryCredentials the temporary credentials
 * @param account the account
 * @return the map
 */
public static Map<String,List<IAMCertificateVH>> fetchIAMCertificateInfo(BasicSessionCredentials temporaryCredentials, String skipRegions, String account, String accountName) {
	log.info("Fetch IAMCertificate info start");
	Map<String,List<IAMCertificateVH>> iamCertificateVH = new LinkedHashMap<>();
	AmazonIdentityManagement amazonIdentityManagement;
	List<ServerCertificateMetadata> listServerCertificatesMetadata = new ArrayList<>();
	String serverCertificateName = null;
	String arn = null;
	Date expiryDate = null;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+account + "\",\"Message\": \"Exception in fetching info for resource \" ,\"type\": \"IAMCertificate\"" ;
		try {
				amazonIdentityManagement = AmazonIdentityManagementClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials))
						.withRegion(InventoryConstants.REGION_US_WEST_2).build();
				listServerCertificatesMetadata = amazonIdentityManagement.listServerCertificates(new ListServerCertificatesRequest())
						.getServerCertificateMetadataList();
				List<IAMCertificateVH> iamCerttList = new ArrayList<>();
				if(!CollectionUtils.isEmpty(listServerCertificatesMetadata)) {
				for (ServerCertificateMetadata serverCertIAMMetadata : listServerCertificatesMetadata) {
					serverCertificateName = serverCertIAMMetadata.getServerCertificateName();
					arn = serverCertIAMMetadata.getArn();
					expiryDate = serverCertIAMMetadata.getExpiration();
					IAMCertificateVH iamCertVH = new IAMCertificateVH();
					iamCertVH.setServerCertificateName(serverCertificateName);
					iamCertVH.setArn(arn);
					iamCertVH.setExpiryDate(expiryDate);
					iamCerttList.add(iamCertVH);
				}
				iamCertificateVH.put(account+delimiter+accountName, iamCerttList);
				}else {
					log.info("List is empty");
				}
		} catch (Exception e) {
			log.error(expPrefix + InventoryConstants.ERROR_CAUSE + e.getMessage() + "\"}");
			ErrorManageUtil.uploadError(account,"", "IAMCertificate", e.getMessage());
		}
	return iamCertificateVH;
}
 
Example #26
Source File: IdentityManagementImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a service implementation using the specified client object.
 *
 * @param client The low-level client which the service implementation will
 *         use to make API calls.
 */
public IdentityManagementImpl(AmazonIdentityManagement client) {
    ServiceModel model = V1ModelLoader.load(IdentityManagement.class,
            IdentityManagement.class.getAnnotation(V1ServiceInterface.class).model());

    this.service = new ServiceImpl<AmazonIdentityManagement>(model, client);
}
 
Example #27
Source File: BasicPlanIam.java    From s3-cf-service-broker with Apache License 2.0 5 votes vote down vote up
@Autowired
public BasicPlanIam(AmazonIdentityManagement iam, BucketGroupPolicy bucketGroupPolicy,
                    @Value("${GROUP_PATH:/cloud-foundry/s3/}") String groupPath,
                    @Value("${GROUP_NAME_PREFIX:cloud-foundry-s3-}") String groupNamePrefix,
                    @Value("${POLICY_NAME_PREFIX:cloud-foundry-s3-}") String policyNamePrefix,
                    @Value("${USER_PATH:/cloud-foundry/s3/}") String userPath,
                    @Value("${USER_NAME_PREFIX:cloud-foundry-s3-}") String userNamePrefix) {
    super(iam, bucketGroupPolicy, groupPath, groupNamePrefix, policyNamePrefix, userPath, userNamePrefix);
}
 
Example #28
Source File: Iam.java    From s3-cf-service-broker with Apache License 2.0 5 votes vote down vote up
@Autowired
public Iam(AmazonIdentityManagement iam, BucketGroupPolicy bucketGroupPolicy,
        @Value("${GROUP_PATH:/cloud-foundry/s3/}") String groupPath,
        @Value("${GROUP_NAME_PREFIX:cloud-foundry-s3-}") String groupNamePrefix,
        @Value("${POLICY_NAME_PREFIX:cloud-foundry-s3-}") String policyNamePrefix,
        @Value("${USER_PATH:/cloud-foundry/s3/}") String userPath,
        @Value("${USER_NAME_PREFIX:cloud-foundry-s3-}") String userNamePrefix) {
    this.iam = iam;
    this.bucketGroupPolicy = bucketGroupPolicy;
    this.groupPath = groupPath;
    this.groupNamePrefix = groupNamePrefix;
    this.policyNamePrefix = policyNamePrefix;
    this.userPath = userPath;
    this.userNamePrefix = userNamePrefix;
}
 
Example #29
Source File: AmazonRdsDataSourceUserTagsFactoryBeanTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void getObject_instanceWithTagsAndNoResourceIdResolverAndDefaultRegion_mapWithTagsReturned()
		throws Exception {
	// Arrange
	AmazonRDS amazonRds = mock(AmazonRDS.class);
	AmazonIdentityManagement amazonIdentityManagement = mock(
			AmazonIdentityManagement.class);

	AmazonRdsDataSourceUserTagsFactoryBean factoryBean = new AmazonRdsDataSourceUserTagsFactoryBean(
			amazonRds, "test", amazonIdentityManagement);

	when(amazonIdentityManagement.getUser()).thenReturn(
			new GetUserResult().withUser(new User("/", "aemruli", "123456789012",
					"arn:aws:iam::1234567890:user/aemruli", new Date())));
	when(amazonRds.listTagsForResource(new ListTagsForResourceRequest()
			.withResourceName("arn:aws:rds:us-west-2:1234567890:db:test")))
					.thenReturn(new ListTagsForResourceResult().withTagList(
							new Tag().withKey("key1").withValue("value1"),
							new Tag().withKey("key2").withValue("value2")));

	// Act
	factoryBean.afterPropertiesSet();
	Map<String, String> userTagMap = factoryBean.getObject();

	// Assert
	assertThat(userTagMap.get("key1")).isEqualTo("value1");
	assertThat(userTagMap.get("key2")).isEqualTo("value2");
}
 
Example #30
Source File: AwsLogRolePermissionValidator.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public void validate(AmazonIdentityManagement iam, InstanceProfile instanceProfile,
        CloudS3View cloudFileSystem, ValidationResultBuilder validationResultBuilder) {
    SortedSet<String> failedActions = new TreeSet<>();

    // TODO need to figure out how to get LOGS_LOCATION_BASE value
    Map<String, String> replacements = Map.ofEntries(
            Map.entry("${LOGS_LOCATION_BASE}", "")
    );

    Policy policy = awsIamService.getPolicy("aws-cdp-log-policy.json", replacements);
    List<Role> roles = instanceProfile.getRoles();
    List<Policy> policies = Collections.singletonList(policy);
    for (Role role : roles) {
        try {
            List<EvaluationResult> evaluationResults = awsIamService.validateRolePolicies(iam,
                    role, policies);
            failedActions.addAll(getFailedActions(role, evaluationResults));
        } catch (AmazonIdentityManagementException e) {
            // Only log the error and keep processing. Failed actions won't be added, but
            // processing doesn't get stopped either. This can happen due to rate limiting.
            LOGGER.error("Unable to validate role policies for role {} due to {}", role.getArn(),
                    e.getMessage(), e);
        }
    }

    if (!failedActions.isEmpty()) {
        validationResultBuilder.error(String.format("The log role (%s) don't have the required permissions: %n%s",
                String.join(", ", roles.stream().map(Role::getArn).collect(Collectors.toCollection(TreeSet::new))),
                String.join("\n", failedActions)));
    }
}