Java Code Examples for com.amazonaws.util.StringUtils#trim()

The following examples show how to use com.amazonaws.util.StringUtils#trim() . 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: EnvironmentAWSCredentialsProvider.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
@Override
public AWSCredentials getCredentials() {
    String accessKey = environment.getProperty(ACCESS_KEY_ENV_VAR, String.class, environment.getProperty(ALTERNATE_ACCESS_KEY_ENV_VAR, String.class, (String) null));

    String secretKey = environment.getProperty(SECRET_KEY_ENV_VAR, String.class, environment.getProperty(ALTERNATE_SECRET_KEY_ENV_VAR, String.class, (String) null));
    accessKey = StringUtils.trim(accessKey);
    secretKey = StringUtils.trim(secretKey);
    String sessionToken = StringUtils.trim(environment.getProperty(AWS_SESSION_TOKEN_ENV_VAR, String.class, (String) null));

    if (StringUtils.isNullOrEmpty(accessKey) || StringUtils.isNullOrEmpty(secretKey)) {
        throw new SdkClientException(
            "Unable to load AWS credentials from environment " +
                "(" + ACCESS_KEY_ENV_VAR + " (or " + ALTERNATE_ACCESS_KEY_ENV_VAR + ") and " +
                SECRET_KEY_ENV_VAR + " (or " + ALTERNATE_SECRET_KEY_ENV_VAR + "))");
    }

    return sessionToken == null ?
        new BasicAWSCredentials(accessKey, secretKey)
        :
        new BasicSessionCredentials(accessKey, secretKey, sessionToken);
}
 
Example 2
Source File: CheckGuardDutyFindingsExists.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * 
 * @param ruleParam
 * 
 *            ************* Following are the Rule Parameters********* <br>
 * <br>
 * 
 *            severity : Enter the value of severity <br>
 * <br>
 * 
 *            ruleCategory : Enter the value of category <br>
 * <br>
 * 
 *            esGuardDutyUrl : Give the guard duty ES url's <br>
 * <br>
 * 
 *            ruleKey : check-guard-duty-findings-exists <br>
 * <br>
 * 
 *            threadsafe : if true , rule will be executed on multiple
 *            threads <br>
 * <br>
 * 
 * @param resourceAttributes
 *            this is a resource in context which needs to be scanned this
 *            is provided by execution engine
 *
 */

public RuleResult execute(final Map<String, String> ruleParam,
        Map<String, String> resourceAttributes) {

    logger.debug("========CheckGuardDutyFindingsExists started=========");
    String resourceId = null;
    Annotation annotation = null;

    String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
    String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
    String guardDutyEsUrl = null;
    
    String formattedUrl = PacmanUtils.formatUrl(ruleParam,PacmanRuleConstants.ES_GUARD_DUTY_URL);
    
    if(!StringUtils.isNullOrEmpty(formattedUrl)){
        guardDutyEsUrl =  formattedUrl;
    }

    MDC.put("executionId", ruleParam.get("executionId")); 
    MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); 
    List<LinkedHashMap<String, Object>> issueList = new ArrayList();
    LinkedHashMap<String, Object> issue = new LinkedHashMap<>();

    if (!PacmanUtils.doesAllHaveValue(severity, category, guardDutyEsUrl)) {
        logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
        throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
    }

    if (resourceAttributes != null) {
        resourceId = StringUtils.trim(resourceAttributes
                .get(PacmanSdkConstants.RESOURCE_ID));
        Boolean isGuardDutyFindingsExists = PacmanUtils
                .isGuardDutyFindingsExists(resourceId, guardDutyEsUrl,
                        PacmanRuleConstants.GUARD_DUTY_INSTANCE_ATTR);

        if (isGuardDutyFindingsExists) {
            annotation = Annotation.buildAnnotation(ruleParam,
                    Annotation.Type.ISSUE);
            annotation.put(PacmanSdkConstants.DESCRIPTION,
                    "Guard Duty findings exists!!");
            annotation.put(PacmanRuleConstants.SEVERITY, severity);
            annotation.put(PacmanRuleConstants.CATEGORY, category);

            issue.put(PacmanRuleConstants.VIOLATION_REASON,
                    "Ec2 instance associated to a guard duty!!");
            issueList.add(issue);
            annotation.put("issueDetails", issueList.toString());
            logger.debug("========CheckGuardDutyFindingsExists ended with annotation {} :=========",annotation);
            return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,
                    PacmanRuleConstants.FAILURE_MESSAGE, annotation);
        }
    }

    logger.debug("========CheckGuardDutyFindingsExists ended=========");

    return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,
            PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 3
Source File: SecurityGroupNotUsedRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * 
 * @param ruleParam ************* Following are the Rule Parameters********* <br><br>
 * 
 * severity : Enter the value of severity <br><br>
 * 
 * ruleCategory : Enter the value of category <br><br>
 * 
 * esServiceWithSgUrl   : Comma separated list of services with sg ES url's <br><br>
 * 
 * splitterChar : The splitter character used to split the mandatory tags <br><br>
 * 
 * ruleKey : check-for-unused-security-group <br><br>
 * 
 * esUrl : Enter the ES url <br><br>
 * 
 * threadsafe : if true , rule will be executed on multiple threads <br><br>
 * 
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
 *
 */

public RuleResult execute(final Map<String, String> ruleParam,Map<String, String> resourceAttributes) {

	logger.debug("========SecurityGroupNotUsedRule started=========");
	String groupId = null;
	Annotation annotation = null;
	
	String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
	String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
	String tagsSplitter = ruleParam.get(PacmanSdkConstants.SPLITTER_CHAR);
	String groupName = resourceAttributes.get(PacmanRuleConstants.GROUP_NAME);
	String serviceWithSgUrls = null;
	String esUrl = ruleParam.get(PacmanRuleConstants.ES_URL_PARAM);
	MDC.put("executionId", ruleParam.get("executionId")); // this is the logback Mapped Diagnostic Contex
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); // this is the logback Mapped Diagnostic Contex
	
	String pacmanHost = PacmanUtils.getPacmanHost(PacmanRuleConstants.ES_URI);

       if (!StringUtils.isNullOrEmpty(pacmanHost)) {
           serviceWithSgUrls = ruleParam.get(PacmanRuleConstants.ES_SERVICES_WITH_SG_URL);
           esUrl = pacmanHost;
       }
	
	List<LinkedHashMap<String,Object>>issueList = new ArrayList<>();
	LinkedHashMap<String,Object>issue = new LinkedHashMap<>();
	
	if (!PacmanUtils.doesAllHaveValue(severity,category,serviceWithSgUrls,tagsSplitter,esUrl)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}
	
	List<String> serviceWithSgUrlsList = PacmanUtils.splitStringToAList(serviceWithSgUrls, tagsSplitter);
	
	if (!resourceAttributes.isEmpty()) {
		groupId = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.GROUP_ID));
		String resource;
		try {
			resource = PacmanUtils.getQueryFromElasticSearch(groupId,serviceWithSgUrlsList,esUrl,ruleParam);
		
		
		if(StringUtils.isNullOrEmpty(resource)){
			annotation = Annotation.buildAnnotation(ruleParam,Annotation.Type.ISSUE);
			annotation.put(PacmanSdkConstants.DESCRIPTION,"Unused security group found!!");
			annotation.put(PacmanRuleConstants.SEVERITY, severity);
			annotation.put(PacmanRuleConstants.SUBTYPE, Annotation.Type.RECOMMENDATION.toString());
			annotation.put(PacmanRuleConstants.CATEGORY, category);
			annotation.put(PacmanRuleConstants.GROUP_NAME, groupName);
			
			issue.put(PacmanRuleConstants.VIOLATION_REASON, "Security group not associated to any of EC2/ApplicationElb/ClassicElb/RDSDB/RDSCluster/RedShift/Lambda/Elasticsearch");
			issueList.add(issue);
			annotation.put("issueDetails",issueList.toString());
			
			logger.debug("========SecurityGroupNotUsedRule ended with an annotation : {}=========",annotation);
			return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE,annotation);
		}
		} catch (Exception e) {
			logger.error("unable to determine",e);
			throw new RuleExecutionFailedExeption("unable to determine"+e);
		}
	}
	
	logger.debug("========SecurityGroupNotUsedRule ended=========");

	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 4
Source File: UnusedClassicElbRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * 
 * @param ruleParam
 * 
 ************** Following are the Rule Parameters********* <br><br>
 * 
 *ruleKey : check-for-unused-classic-elb <br><br>
 *
 *esClassicElbWithInstanceUrl : Enter the classic elb with instance es api <br><br>
 *
 *threadsafe : if true , rule will be executed on multiple threads <br><br>
 *
 *severity : Enter the value of severity <br><br>
 * 
 *ruleCategory : Enter the value of category <br><br>
 *
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
 *
 */

public RuleResult execute(final Map<String, String> ruleParam,Map<String, String> resourceAttributes) {
	logger.debug("========UnusedClassicElbRule started=========");
	String classicLoadBalncerId = null;
	String region = null;
	
	String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
	String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
	String classicElbUrl = null;
	
	MDC.put("executionId", ruleParam.get("executionId")); // this is the logback Mapped Diagnostic Contex
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); // this is the logback Mapped Diagnostic Contex
	
	String formattedUrl = PacmanUtils.formatUrl(ruleParam,PacmanRuleConstants.ES_CLASSIC_ELB_WITH_INSTANCE_URL);
       
       if(!StringUtils.isNullOrEmpty(formattedUrl)){
           classicElbUrl =  formattedUrl;
       }
	
	if (!PacmanUtils.doesAllHaveValue(severity,category,classicElbUrl)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}
	
	if (resourceAttributes != null) {
		classicLoadBalncerId = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.LOAD_BALANCER_ID_ATTRIBUTE));
		region = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.REGION_ATTR));
		boolean isClassicElbWithEc2Exists = false;
		try {
			isClassicElbWithEc2Exists = PacmanUtils.checkResourceIdFromElasticSearch(classicLoadBalncerId,classicElbUrl,PacmanRuleConstants.LOAD_BALANCER_ID_ATTRIBUTE,region);
		} catch (Exception e) {
			logger.error("unable to determine",e);
			throw new RuleExecutionFailedExeption("unable to determine"+e);
		}
		if (!isClassicElbWithEc2Exists) {
			String description = "Unused Classic ELB found!!";
            return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, PacmanUtils.createELBAnnotation("Classic",ruleParam, description,severity,category));
		}
	}
	logger.debug("========UnusedClassicElbRule ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 5
Source File: UnusedApplicationElbRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * 
 * @param ruleParam
 * 
 ************** Following are the Rule Parameters********* <br><br>
 * 
 *ruleKey : check-for-unused-application-elb <br><br>
 *
 *esAppElbWithInstanceUrl : Enter the application elb with instance api <br><br>
 *
 *threadsafe : if true , rule will be executed on multiple threads <br><br>
 *
 *severity : Enter the value of severity <br><br>
 * 
 *ruleCategory : Enter the value of category <br><br>
 *
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
 *
 */

public RuleResult execute(final Map<String, String> ruleParam,Map<String, String> resourceAttributes) {

	logger.debug("========UnusedApplicationElbRule started=========");
	String applLoadBalncerId = null;
	String region = null;
	String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
	String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
	String appElbUrl = null;
	
	MDC.put("executionId", ruleParam.get("executionId")); // this is the logback Mapped Diagnostic Contex
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); // this is the logback Mapped Diagnostic Contex
	
	String formattedUrl = PacmanUtils.formatUrl(ruleParam,PacmanRuleConstants.ES_APPLELB_WITH_INSTANCE_URL);
       
       if(!StringUtils.isNullOrEmpty(formattedUrl)){
           appElbUrl =  formattedUrl;
       }
	
	if (!PacmanUtils.doesAllHaveValue(severity,category,appElbUrl)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}
	
	if (resourceAttributes != null) {
		applLoadBalncerId = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.LOAD_BALANCER_ID_ATTRIBUTE));
		region = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.REGION_ATTR));
		boolean isApplicationElbWithEc2Exists = false;
		try {
			isApplicationElbWithEc2Exists = PacmanUtils.checkResourceIdFromElasticSearch(applLoadBalncerId,appElbUrl,PacmanRuleConstants.LOAD_BALANCER_ID_ATTRIBUTE,region);
		} catch (Exception e) {
			logger.error("unable to determine",e);
			throw new RuleExecutionFailedExeption("unable to determine"+e);
		}
		if (!isApplicationElbWithEc2Exists) {
		    String description = "Unused Application ELB found!!";
			return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, PacmanUtils.createELBAnnotation("Application",ruleParam, description,severity,category));
		}
		}
	logger.debug("========UnusedApplicationElbRule ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 6
Source File: SSLCertificateExpiryRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * 
 * @param ruleParam
 * 
 **************Following are the Rule Parameters********* <br><br>
 * 
 * ruleKey : check-for-ssl_certificate-expiry <br><br>
 *
 * threadsafe : if true , rule will be executed on multiple threads <br><br>
 *
 * targetExpireDuration : specify the expiry duration in numbers <br><br>
 * 
 * severity : Enter the value of severity <br><br>
 * 
 * ruleCategory : Enter the value of category <br><br>
 *
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
 *
 */

public RuleResult execute(final Map<String, String> ruleParam,Map<String, String> resourceAttributes) {
	logger.debug("========SSLCertificateExpiryRule started=========");
	Annotation annotation = null;
	String validTo = null;
	long expiredDuration;
	long targetExpiredDuration;
	String targetExpiryDurationInString = ruleParam.get(PacmanRuleConstants.EXPIRED_DURATION);
	
	String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
	String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
	
	MDC.put("executionId", ruleParam.get("executionId")); // this is the logback Mapped Diagnostic Contex
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); // this is the logback Mapped Diagnostic Contex
	
	List<LinkedHashMap<String,Object>>issueList = new ArrayList<>();
	LinkedHashMap<String,Object>issue = new LinkedHashMap<>();

	if (!PacmanUtils.doesAllHaveValue(targetExpiryDurationInString,severity,category)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}

	if (resourceAttributes != null) {
		validTo = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.VALID_TO));

		expiredDuration = calculateSslExpiredDuration(validTo);
		targetExpiredDuration = Long.parseLong(targetExpiryDurationInString);
		if (expiredDuration > 0) {
			if (expiredDuration <= targetExpiredDuration) {
				annotation = Annotation.buildAnnotation(ruleParam,Annotation.Type.ISSUE);
				annotation.put(PacmanSdkConstants.DESCRIPTION,"SSL Expiry within "+ targetExpiryDurationInString+ " days found!!");
				annotation.put(PacmanRuleConstants.SEVERITY, severity);
				annotation.put(PacmanRuleConstants.CATEGORY, category);
				
				issue.put(PacmanRuleConstants.VIOLATION_REASON, "SSL Expiry within "+ targetExpiryDurationInString+ " days found!!");
				issueList.add(issue);
				annotation.put("issueDetails",issueList.toString());
				logger.debug("========SSLCertificateExpiryRule ended with annotation {} : =========",annotation);
				return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, annotation);
			}
		} else {
			logger.info("Elb with SSL validity not expired");
		}
	}
	logger.debug("========SSLCertificateExpiryRule ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 7
Source File: CheckForIdleLoadBalancersRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * @param ruleParam 
 * 
 * ************* Following are the Rule Parameters********* <br><br>
 * 
 * checkId   : Mention the checkId value <br><br>
 * 
 * ruleKey : check-for-idle-load-balancers <br><br>
 * 
 * esServiceURL : Enter the Es url <br><br>
 * 
 * threadsafe : if true , rule will be executed on multiple threads <br><br>
 *  
 * severity : Enter the value of severity <br><br>
 * 
 * ruleCategory : Enter the value of category <br><br>
 * 
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
 *
 */
@Override
public RuleResult execute(Map<String, String> ruleParam, Map<String, String> resourceAttributes) {
	
	logger.debug("========CheckForIdleLoadBalancersRule started=========");
	Annotation annotation = null;
	String loadBalancerId = null;
	String region = null;
	String accountId = null;
	String checkId = StringUtils.trim(ruleParam.get(PacmanRuleConstants.CHECK_ID));
	
	String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
	String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
	
	String serviceEsURL = null;
	
	String formattedUrl = PacmanUtils.formatUrl(ruleParam,PacmanRuleConstants.ES_CHECK_SERVICE_SEARCH_URL_PARAM);
       
       if(!StringUtils.isNullOrEmpty(formattedUrl)){
           serviceEsURL =  formattedUrl;
       }

       MDC.put("executionId", ruleParam.get("executionId")); // this is the logback Mapped Diagnostic Contex
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); // this is the logback Mapped Diagnostic Contex
	
	List<LinkedHashMap<String,Object>>issueList = new ArrayList<>();
	LinkedHashMap<String,Object>issue = new LinkedHashMap<>();
	
	if (!PacmanUtils.doesAllHaveValue(checkId,severity,category,serviceEsURL)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}
	
	
	
	if (resourceAttributes != null) {
		region = resourceAttributes.get(PacmanRuleConstants.REGION);
		accountId = resourceAttributes.get(PacmanSdkConstants.ACCOUNT_ID);
		loadBalancerId = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.LOAD_BALANCER_ID_ATTRIBUTE));
		Map<String, String> idleLoadBalancerMap = new HashMap<>();
		try {
			idleLoadBalancerMap = PacmanUtils.getIdleLoadBalancerDetails(checkId,loadBalancerId,serviceEsURL,region,accountId);
		} catch (Exception e) {
			logger.error("unable to determine",e);
			throw new RuleExecutionFailedExeption("unable to determine"+e);
		}
		if (!idleLoadBalancerMap.isEmpty()) {
			annotation = Annotation.buildAnnotation(ruleParam, Annotation.Type.ISSUE);
			annotation.put(PacmanSdkConstants.DESCRIPTION,"Idle load balancer found !");
			annotation.put(PacmanRuleConstants.SEVERITY, severity);
			annotation.put(PacmanRuleConstants.CATEGORY, category);
			annotation.put(PacmanRuleConstants.EST_MONTHLY_SAVINGS, idleLoadBalancerMap.get(PacmanRuleConstants.EST_MONTHLY_SAVINGS));
			annotation.put(PacmanRuleConstants.REASON, idleLoadBalancerMap.get(PacmanRuleConstants.REASON));
			
			issue.put(PacmanRuleConstants.VIOLATION_REASON,	"Idle load balancer found!!");
			issue.put(PacmanRuleConstants.CHECKID, checkId);
			issue.put(PacmanRuleConstants.SOURCE_VERIFIED, "trusted advisor");
			issueList.add(issue);
			annotation.put("issueDetails", issueList.toString());
			logger.debug("========CheckForIdleLoadBalancersRule ended with annotaion {} :=========",annotation);
			return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, annotation);
		}
		}
	logger.debug("========CheckForIdleLoadBalancersRule ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 8
Source File: UnderutilizedAmazonEBSVolumesRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * @param ruleParam 
 * 
 * ************* Following are the Rule Parameters********* <br><br>
 * 
 * checkId   : Mention the checkId value <br><br>
 * 
 * ruleKey : check-for-underutilized-EBS-Volumes <br><br>
 * 
 * esServiceURL : Enter service URL <br><br>
 * 
 * threadsafe : if true , rule will be executed on multiple threads <br><br>
 *  
 * severity : Enter the value of severity <br><br>
 * 
 * ruleCategory : Enter the value of category <br><br>
 * 
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
 *
 */
@Override
public RuleResult execute(Map<String, String> ruleParam, Map<String, String> resourceAttributes) {
	
	logger.debug("========UnderutilizedAmazonEBSVolumesRule started=========");
	Annotation annotation = null;
	String resourceId = null;
	String region = null;
	String accountId = null;
	String checkId = StringUtils.trim(ruleParam.get(PacmanRuleConstants.CHECK_ID));
	
	String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
	String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
	
	String serviceEsURL = null;
	
	String formattedUrl = PacmanUtils.formatUrl(ruleParam,PacmanRuleConstants.ES_CHECK_SERVICE_SEARCH_URL_PARAM);
       
       if(!StringUtils.isNullOrEmpty(formattedUrl)){
           serviceEsURL =  formattedUrl;
       }

       String desc=null;
	MDC.put("executionId", ruleParam.get("executionId")); // this is the logback Mapped Diagnostic Contex
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); // this is the logback Mapped Diagnostic Contex
	
	List<LinkedHashMap<String,Object>>issueList = new ArrayList<>();
	LinkedHashMap<String,Object>issue = new LinkedHashMap<>();
	
	if (!PacmanUtils.doesAllHaveValue(checkId,severity,category,serviceEsURL)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}
	
	if (resourceAttributes != null) {
		region = resourceAttributes.get(PacmanRuleConstants.REGION);
		accountId = resourceAttributes.get(PacmanSdkConstants.ACCOUNT_ID);
		resourceId = StringUtils.trim(resourceAttributes.get("_resourceid"));
		Map<String, String> infoFromTA =null;
		try {
			infoFromTA = PacmanUtils.getEBSVolumeWithCheckId(checkId,resourceId,serviceEsURL,region,accountId);
		} catch (Exception e) {
			logger.error("unable to determine",e);
			throw new RuleExecutionFailedExeption("unable to determine"+e);
		}
		if (!infoFromTA.isEmpty()) {
			desc ="Amazon EBS Volume "+resourceId+" Underutilized";
			annotation = Annotation.buildAnnotation(ruleParam, Annotation.Type.ISSUE);
			annotation.put(PacmanSdkConstants.DESCRIPTION,desc);
			annotation.put(PacmanRuleConstants.SEVERITY, severity);
			annotation.put(PacmanRuleConstants.CATEGORY, category);
			issue.put(PacmanRuleConstants.VIOLATION_REASON, desc);
			issue.put(PacmanRuleConstants.SOURCE_VERIFIED, "Trusted Advisor");
			issue.put("info_from_trusted_advisor", new Gson().toJson(infoFromTA));
			issueList.add(issue);
			annotation.put("issueDetails",issueList.toString());
			logger.debug("========UnderutilizedAmazonEBSVolumesRule ended with annotation {} :=========",annotation);
			return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, annotation);
		}
		}
	logger.debug("========UnderutilizedAmazonEBSVolumesRule ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 9
Source File: UnusedElasticIpRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * 
 * @param ruleParam
 * 
 ************** Following are the Rule Parameters********* <br><br>
 * 
 * ruleKey : check-for-unused-elastic-ip <br><br>
 * 
 * threadsafe   : if true , rule will be executed on multiple threads <br><br>
 *
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
 *
 */

public RuleResult execute(final Map<String, String> ruleParam,Map<String, String> resourceAttributes) {

	logger.debug("========UnusedElasticIpRule started=========");
	Annotation annotation = null;
	String associationId = null;
	String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
	String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
	
	
	MDC.put("executionId", ruleParam.get("executionId")); // this is the logback Mapped Diagnostic Contex
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); // this is the logback Mapped Diagnostic Contex
	
	List<LinkedHashMap<String,Object>>issueList = new ArrayList<>();
	LinkedHashMap<String,Object>issue = new LinkedHashMap<>();
	
	if (!PacmanUtils.doesAllHaveValue(severity,category)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}

	if (resourceAttributes != null) {
		associationId = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.ASSOCIATION_ID));
          
		if (StringUtils.isNullOrEmpty(associationId)) {
			annotation = Annotation.buildAnnotation(ruleParam,Annotation.Type.ISSUE);
			annotation.put(PacmanSdkConstants.DESCRIPTION,"Unused Elastic Ip found!!");
			annotation.put(PacmanRuleConstants.SEVERITY, severity);
			annotation.put(PacmanRuleConstants.SUBTYPE, Annotation.Type.RECOMMENDATION.toString());
			annotation.put(PacmanRuleConstants.CATEGORY, category);
			annotation.put(PacmanRuleConstants.ALLOCATION_ID, resourceAttributes.get(PacmanRuleConstants.ALLOCATION_ID));
			issue.put(PacmanRuleConstants.VIOLATION_REASON, "ElasticIp doesn't associated to an EC2 instance!!");
			issueList.add(issue);
			annotation.put("issueDetails",issueList.toString());
			logger.debug("========UnusedElasticIpRule ended with annotation {} :=========",annotation);
			return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, annotation);
		}
	}
	logger.debug("========UnusedElasticIpRule ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 10
Source File: UnusedEBSRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * 
 * @param ruleParam
 * 
 ************** Following are the Rule Parameters********* <br><br>
 * 
 * ruleKey : check-for-unused-ebs-rule <br><br>
 *
 * threadsafe : if true , rule will be executed on multiple threads <br><br>
 *
 * esEbsWithInstanceUrl : Enter the ebs es api <br><br>
 *
 * severity : Enter the value of severity <br><br>
 * 
 * ruleCategory : Enter the value of category <br><br>
 * 
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
 *
 */

public RuleResult execute(final Map<String, String> ruleParam,Map<String, String> resourceAttributes) {
	
	logger.debug("========UnusedEBSRule started=========");

	Annotation annotation = null;
	String volumeId = null;
	String region = null;
	String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
	String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
	String ebsUrl = null;
	
	String formattedUrl = PacmanUtils.formatUrl(ruleParam,PacmanRuleConstants.ES_EBS_WITH_INSTANCE_URL);
       
       if(!StringUtils.isNullOrEmpty(formattedUrl)){
           ebsUrl =  formattedUrl;
       }
	
	MDC.put("executionId", ruleParam.get("executionId")); // this is the logback Mapped Diagnostic Contex
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); // this is the logback Mapped Diagnostic Contex
	
	List<LinkedHashMap<String,Object>>issueList = new ArrayList<>();
	LinkedHashMap<String,Object>issue = new LinkedHashMap<>();
	
	if (!PacmanUtils.doesAllHaveValue(severity,category,ebsUrl)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}

	if (resourceAttributes != null) {
		volumeId = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.VOLUME_ID));
		region = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.REGION_ATTR));
		boolean isEbsWithEc2Exists = false;
		try{
		 isEbsWithEc2Exists = PacmanUtils.checkResourceIdFromElasticSearch(volumeId,ebsUrl,PacmanRuleConstants.VOLUME_ID,region);
		} catch (Exception e) {
			logger.error("unable to determine",e);
			throw new RuleExecutionFailedExeption("unable to determine"+e);
		}
		if (!isEbsWithEc2Exists) {
			annotation = Annotation.buildAnnotation(ruleParam,Annotation.Type.ISSUE);
			annotation.put(PacmanSdkConstants.DESCRIPTION,"Unused EBS found!!");
			annotation.put(PacmanRuleConstants.SEVERITY, severity);
			annotation.put(PacmanRuleConstants.SUBTYPE, Annotation.Type.RECOMMENDATION.toString());
			annotation.put(PacmanRuleConstants.CATEGORY, category);
			
			issue.put(PacmanRuleConstants.VIOLATION_REASON, "EBS volume is not attached to an ec2 instance");
			issueList.add(issue);
			annotation.put("issueDetails",issueList.toString());
			logger.debug("========UnusedEBSRule ended with annotation {} :=========",annotation);
			return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, annotation);
		}
	}
	logger.debug("========UnusedEBSRule ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 11
Source File: ServiceLimitRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * @param ruleParam 
 * 
 * ************* Following are the Rule Parameters********* <br><br>
 * 
 * checkId   : Mention the checkId value <br><br>
 * 
 * ruleKey : check-for-service-limit <br><br>
 * 
 * esServiceURL : Enter the service Es url <br><br>
 * 
 * threadsafe : if true , rule will be executed on multiple threads <br><br>
 *  
 * severity : Enter the value of severity <br><br>
 * 
 * ruleCategory : Enter the value of category <br><br>
 * 
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
 *
 */
@Override
public RuleResult execute(Map<String, String> ruleParam, Map<String, String> resourceAttributes) {
	
	logger.debug("========ServiceLimitRule started=========");
	Annotation annotation = null;
	String accountId = null;
	String checkId = StringUtils.trim(ruleParam.get(PacmanRuleConstants.CHECK_ID));
	
	String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
	String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
	String serviceEsURL = null;
	
	String formattedUrl = PacmanUtils.formatUrl(ruleParam,PacmanRuleConstants.ES_CHECK_SERVICE_SEARCH_URL_PARAM);
       
       if(!StringUtils.isNullOrEmpty(formattedUrl)){
           serviceEsURL =  formattedUrl;
       }
	
	MDC.put("executionId", ruleParam.get("executionId")); // this is the logback Mapped Diagnostic Contex
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); // this is the logback Mapped Diagnostic Contex
	
	Gson gson = new Gson();
	List<LinkedHashMap<String,Object>>issueList = new ArrayList<>();
	LinkedHashMap<String,Object>issue = new LinkedHashMap<>();
	
	if (!PacmanUtils.doesAllHaveValue(checkId,severity,category,serviceEsURL)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}
	
	if (resourceAttributes != null) {
		accountId = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.ACCOUNTID));
		Map<String,String> serviceLimitMap = PacmanUtils.getSeviceLimit(checkId,accountId,serviceEsURL);
		if (!serviceLimitMap.isEmpty()) {
			annotation = Annotation.buildAnnotation(ruleParam, Annotation.Type.ISSUE);
			annotation.put(PacmanSdkConstants.DESCRIPTION,"Service limit exceeded for: "+serviceLimitMap);
			annotation.put(PacmanRuleConstants.SEVERITY, severity);
			annotation.put(PacmanRuleConstants.CATEGORY, category);
			for (Map.Entry<String, String> entry : serviceLimitMap.entrySet()) {
				if (!entry.getKey().equalsIgnoreCase(PacmanRuleConstants.SERVICE_LIMIT_STATUS_RED)) {
				annotation.put(entry.getKey(), entry.getValue());
				}
				if (entry.getKey().equalsIgnoreCase(PacmanRuleConstants.SERVICE_LIMIT_STATUS_RED)) {
					annotation.put(PacmanSdkConstants.SECURITY,PacmanSdkConstants.SEV_HIGH);
				}
			}
			
			issue.put(PacmanRuleConstants.VIOLATION_REASON, "Service limit exceeded");
			issue.put("service_limit", gson.toJson(serviceLimitMap) );
			issue.put(PacmanRuleConstants.CHECKID, checkId);
			issue.put(PacmanRuleConstants.SOURCE_VERIFIED, "trusted advisor");
			issueList.add(issue);
			annotation.put("issueDetails",issueList.toString());

			logger.debug("========ServiceLimitRule ended with an annotation : {}=======", annotation);
			return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, annotation);
		}
		}
	logger.debug("========ServiceLimitRule ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 12
Source File: AmazonRDSIdleDBInstancesRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * @param ruleParam 
 * 
 * ************* Following are the Rule Parameters********* <br><br>
 * 
 * checkId   : Mention the checkId value <br><br>
 * 
 * ruleKey : check-for-amazon-RDS-idle-DB-instances <br><br>
 * 
 * esServiceURL : Enter the Es url <br><br>
 * 
 * threadsafe : if true , rule will be executed on multiple threads <br><br>
 *  
 * severity : Enter the value of severity <br><br>
 * 
 * ruleCategory : Enter the value of category <br><br>
 * 
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
 *
 */
@Override
public RuleResult execute(Map<String, String> ruleParam, Map<String, String> resourceAttributes) {
	
	logger.debug("========AmazonRDSIdleDBInstancesRule started=========");
	Annotation annotation = null;
	String resourceId = null;
	String region = null;
	String accountId = null;
	String checkId = StringUtils.trim(ruleParam.get(PacmanRuleConstants.CHECK_ID));
	
	String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
	String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
	
	String serviceEsURL = null;
	
	String formattedUrl = PacmanUtils.formatUrl(ruleParam,PacmanRuleConstants.ES_CHECK_SERVICE_SEARCH_URL_PARAM);
       
       if(!StringUtils.isNullOrEmpty(formattedUrl)){
           serviceEsURL =  formattedUrl;
       }
	
	MDC.put("executionId", ruleParam.get("executionId")); // this is the logback Mapped Diagnostic Contex
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); // this is the logback Mapped Diagnostic Contex
	
	List<LinkedHashMap<String,Object>>issueList = new ArrayList<>();
	LinkedHashMap<String,Object>issue = new LinkedHashMap<>();
	
	if (!PacmanUtils.doesAllHaveValue(checkId,severity,category,serviceEsURL)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}
	
	if (resourceAttributes != null) {
		region = resourceAttributes.get(PacmanRuleConstants.REGION);
		accountId = resourceAttributes.get(PacmanSdkConstants.ACCOUNT_ID);
		resourceId = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.DB_INSTANCE_IDENTIFIER));
		Map<String, String> rdsIdleDbMap = new HashMap<>();
		try {
			rdsIdleDbMap = PacmanUtils.getRDSDetailsForCheckId(checkId,resourceId,serviceEsURL,region,accountId);
		} catch (Exception e) {
			logger.error("unable to determine",e);
			throw new RuleExecutionFailedExeption("unable to determine"+e);
		}
		if (!rdsIdleDbMap.isEmpty()) {
			annotation = Annotation.buildAnnotation(ruleParam, Annotation.Type.ISSUE);
			annotation.put(PacmanSdkConstants.DESCRIPTION,"Amazon RDS idle DB instance found !!");
			annotation.put(PacmanRuleConstants.SEVERITY, severity);
			annotation.put(PacmanRuleConstants.CATEGORY, category);
			annotation.put(PacmanRuleConstants.EST_MONTHLY_SAVINGS, rdsIdleDbMap.get(PacmanRuleConstants.EST_MONTHLY_SAVINGS));
			annotation.put(PacmanRuleConstants.INSTANCETYPE, rdsIdleDbMap.get(PacmanRuleConstants.INSTANCETYPE));
			annotation.put("multi-AZ", rdsIdleDbMap.get("multi-AZ"));
			annotation.put("storageProvisioned", rdsIdleDbMap.get("storageProvisioned"));
			annotation.put("daysSinceLastConnection", rdsIdleDbMap.get("daysSinceLastConnection"));
			
			issue.put(PacmanRuleConstants.VIOLATION_REASON, "Amazon RDS idle DB instance found");
			issue.put(PacmanRuleConstants.CHECKID, checkId);
			issue.put(PacmanRuleConstants.SOURCE_VERIFIED, "trusted advisor");
			issueList.add(issue);
			
			annotation.put("issueDetails",issueList.toString());
			
			logger.debug("========AmazonRDSIdleDBInstancesRule ended with an annotation {} :=========",annotation);
			return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, annotation);
		}
		}
	logger.debug("========AmazonRDSIdleDBInstancesRule ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 13
Source File: UnownedAdGroupsRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * 
 * @param ruleParam
 * 
 *            ************* Following are the Rule Parameters********* <br>
 * <br>
 * 
 *            ruleKey : check-for-unowned-adgroups <br>
 * <br>
 * 
 *            esAdGroupURL : Enter the Es url <br>
 * <br>
 * 
 *            threadsafe : if true , rule will be executed on multiple
 *            threads <br>
 * <br>
 * 
 *            severity : Enter the value of severity <br>
 * <br>
 * 
 *            ruleCategory : Enter the value of category <br>
 * <br>
 * 
 * @param resourceAttributes
 *            this is a resource in context which needs to be scanned this
 *            is provided by execution engine
 *
 */
@Override
public RuleResult execute(Map<String, String> ruleParam,
        Map<String, String> resourceAttributes) {

    logger.debug("========UnownedAdGroupsRule started=========");
    Annotation annotation = null;
    String resourceId = null;

    String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
    String category = ruleParam.get(PacmanRuleConstants.CATEGORY);

    String adGroupEsURL = null;
    
    String formattedUrl = PacmanUtils.formatUrl(ruleParam,PacmanRuleConstants.ES_ADGROUP_URL);
    
    if(!StringUtils.isNullOrEmpty(formattedUrl)){
        adGroupEsURL =  formattedUrl;
    }

    MDC.put("executionId", ruleParam.get("executionId")); 
    // this is the logback Mapped Diagnostic Contex
    MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); 
    // this is the logback Mapped Diagnostic Contex

    List<LinkedHashMap<String, Object>> issueList = new ArrayList<>();
    LinkedHashMap<String, Object> issue = new LinkedHashMap<>();

    if (!PacmanUtils.doesAllHaveValue(severity, category, adGroupEsURL)) {
        logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
        throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
    }

    if (resourceAttributes != null) {
        resourceId = StringUtils.trim(resourceAttributes
                .get(PacmanSdkConstants.RESOURCE_ID));
        Boolean isUnownedAdGroup = false;
        try {
            isUnownedAdGroup = PacmanUtils.getUnownedAdGroup(resourceId,
                    adGroupEsURL);
        } catch (Exception e) {
            logger.error("unable to determine" , e);
            throw new RuleExecutionFailedExeption("unable to determine" + e);
        }
        if (isUnownedAdGroup) {
            annotation = Annotation.buildAnnotation(ruleParam,
                    Annotation.Type.ISSUE);
            annotation.put(PacmanSdkConstants.DESCRIPTION,
                    "Unowned Ad group found !!");
            annotation.put(PacmanRuleConstants.SEVERITY, severity);
            annotation.put(PacmanRuleConstants.CATEGORY, category);

            issue.put(PacmanRuleConstants.VIOLATION_REASON,
                    "AD group doesn't manged by any group or it has svc_adds_unowned value!!");
            issueList.add(issue);
            annotation.put("issueDetails", issueList.toString());
            logger.debug(
                    "========UnownedAdGroupsRule ended with annotation : {}=========",
                    annotation);
            return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,
                    PacmanRuleConstants.FAILURE_MESSAGE, annotation);
        }
    }
    logger.debug("========UnownedAdGroupsRule ended=========");
    return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,
            PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 14
Source File: CheckNestedRolesRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * 
 * @param ruleParam
 * 
 *            ************* Following are the Rule Parameters********* <br>
 * <br>
 * 
 *            ruleKey : check-for-nested-roles <br>
 * <br>
 * 
 *            esAdGroupURL : Enter the Es url <br>
 * <br>
 * 
 *            threadsafe : if true , rule will be executed on multiple
 *            threads <br>
 * <br>
 * 
 *            severity : Enter the value of severity <br>
 * <br>
 * 
 *            ruleCategory : Enter the value of category <br>
 * <br>
 * 
 * @param resourceAttributes
 *            this is a resource in context which needs to be scanned this
 *            is provided by execution engine
 *
 */
@Override
public RuleResult execute(Map<String, String> ruleParam,
        Map<String, String> resourceAttributes) {

    logger.debug("========CheckNestedRolesRule started=========");
    Annotation annotation = null;
    String resourceId = null;

    String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
    String category = ruleParam.get(PacmanRuleConstants.CATEGORY);

    String adGroupEsURL = null;
    
    String formattedUrl = PacmanUtils.formatUrl(ruleParam,PacmanRuleConstants.ES_ADGROUP_URL); 
    
    if(!StringUtils.isNullOrEmpty(formattedUrl)){
        adGroupEsURL =  formattedUrl;
    }

    MDC.put("executionId", ruleParam.get("executionId")); 
    // this is the logback Mapped Diagnostic Contex
    MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID));
    // this is the logback Mapped Diagnostic Contex

    List<LinkedHashMap<String, Object>> issueList = new ArrayList<>();
    LinkedHashMap<String, Object> issue = new LinkedHashMap<>();

    if (!PacmanUtils.doesAllHaveValue(severity, category, adGroupEsURL)) {
        logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
        throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
    }

    if (resourceAttributes != null) {
        resourceId = StringUtils.trim(resourceAttributes
                .get(PacmanSdkConstants.RESOURCE_ID));
        if (resourceId.startsWith(PacmanRuleConstants.ROLE)) {
            Boolean isNestedRole = false;
            try {
                isNestedRole = PacmanUtils.getNestedRoles(resourceId,
                        adGroupEsURL, "nested");
            } catch (Exception e) {
                logger.error("unable to determine" ,e);
                throw new RuleExecutionFailedExeption("unable to determine" + e);
            }
            if (isNestedRole) {
                annotation = Annotation.buildAnnotation(ruleParam,
                        Annotation.Type.ISSUE);
                annotation.put(PacmanSdkConstants.DESCRIPTION,
                        "Nested role found !!");
                annotation.put(PacmanRuleConstants.SEVERITY, severity);
                annotation.put(PacmanRuleConstants.CATEGORY, category);

                issue.put(PacmanRuleConstants.VIOLATION_REASON,
                        "Role is member of another role found!!");
                issueList.add(issue);
                annotation.put("issueDetails", issueList.toString());
                logger.debug(
                        "========CheckNestedRolesRule with annotation : {}=========",
                        annotation);
                return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,
                        PacmanRuleConstants.FAILURE_MESSAGE, annotation);
            }
        }
    }
    logger.debug("========CheckNestedRolesRule ended=========");
    return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,
            PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 15
Source File: EC2withSeverityVulnerabilityRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * 
 * @param ruleParam
 * 
 **************Following are the Rule Parameters********* <br><br>
 * 
 *  ruleKey : check-for-ec2-with-s5-vulnerabilities <br><br>
 *
 *  threadsafe : if true , rule will be executed on multiple threads <br><br>
 *
 *  severity : Enter the value of severity <br><br>
 * 
 *  ruleCategory : Enter the value of category <br><br>
 *
 *  esEc2WithVulnInfoForS5Url : Enter the EC2 with Vuln info ES API <br><br>
 *
 *  severityVulnValue : Enter the severity level such as S5,S4 or S3 <br><br>
 *
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
 *
 */

public RuleResult execute(final Map<String, String> ruleParam, Map<String, String> resourceAttributes) {
	logger.debug("========EC2withSeverityVulnerabilityRule started=========");
	Annotation annotation = null;
	String instanceId = null;

	String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
	String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
	String ec2WithVulnInfoForS5Url = null;
	String severityVulnValue = ruleParam.get(PacmanRuleConstants.SEVERITY_VULN);
	
	String formattedUrl = PacmanUtils.formatUrl(ruleParam,PacmanRuleConstants.ES_EC2_WITH_VULN_INFO_S5_URL);
       
       if(!StringUtils.isNullOrEmpty(formattedUrl)){
           ec2WithVulnInfoForS5Url =  formattedUrl;
       }

	MDC.put("executionId", ruleParam.get("executionId")); 
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); 
	
	List<LinkedHashMap<String,Object>>issueList = new ArrayList<>();
	LinkedHashMap<String,Object>issue = new LinkedHashMap<>();

	if (!PacmanUtils.doesAllHaveValue(severity, category,ec2WithVulnInfoForS5Url, severityVulnValue)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}

	if (resourceAttributes != null) {
		instanceId = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.INSTANCEID));
		try {
			List<String> severityList = PacmanUtils.getSeverityVulnerabilitiesByInstanceId(instanceId,ec2WithVulnInfoForS5Url, severityVulnValue);
			if (!severityList.isEmpty()) {
				
				annotation = Annotation.buildAnnotation(ruleParam,Annotation.Type.ISSUE);
				annotation.put(PacmanSdkConstants.DESCRIPTION,"An Ec2 instance with vulnerability "+ severityVulnValue + " found!!");
				annotation.put(PacmanRuleConstants.SEVERITY, severity);
				annotation.put(PacmanRuleConstants.CATEGORY, category);
				
				issue.put(PacmanRuleConstants.VIOLATION_REASON, "An Ec2 instance with vulnerability "+ severityVulnValue + " found!!");
				issue.put("voilation_title", String.join(",", severityList));
				issueList.add(issue);
				annotation.put("issueDetails",issueList.toString());
				
				logger.debug("========EC2withSeverityVulnerabilityRule ended with an annotation {} : =========", annotation);
				return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, annotation);

			}
		} catch (Exception e) {
			logger.error("error", e);
			throw new RuleExecutionFailedExeption(e.getMessage());
		}

	}
	logger.debug("========EC2withSeverityVulnerabilityRule ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 16
Source File: ResourceScannedByQualysRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters.
 *
 * @param ruleParam ************* Following are the Rule Parameters********* <br><br>
 * 
 * ruleKey : check-for-resource-scanned-by-qualys <br><br>
 * 
 * target : Enter the target days <br><br>
 * 
 * discoveredDaysRange : Enter the discovered days Range <br><br>
 * 
 * esQualysUrl : Enter the qualys URL <br><br>
 * 
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
 * @return the rule result
 */

public RuleResult execute(final Map<String, String> ruleParam,Map<String, String> resourceAttributes) {
	logger.debug("========ResourceScannedByQualysRule started=========");
	Annotation annotation = null;
	String instanceId = null;
	String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
	String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
	String target = ruleParam.get(PacmanRuleConstants.TARGET);
	String firstDiscoveredOn = resourceAttributes.get(PacmanRuleConstants.FIRST_DISCOVERED_ON);
	String discoveredDaysRange = ruleParam.get(PacmanRuleConstants.DISCOVERED_DAYS_RANGE);
	if(!StringUtils.isNullOrEmpty(firstDiscoveredOn)){
	firstDiscoveredOn= firstDiscoveredOn.substring(0,PacmanRuleConstants.FIRST_DISCOVERED_DATE_FORMAT_LENGTH);
	}
	String qualysApi =  null;
	
	String formattedUrl = PacmanUtils.formatUrl(ruleParam,PacmanRuleConstants.ES_QUALYS_URL);
       
       if(!StringUtils.isNullOrEmpty(formattedUrl)){
           qualysApi =  formattedUrl;
       }
       
	MDC.put("executionId", ruleParam.get("executionId")); // this is the logback Mapped Diagnostic Contex
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); // this is the logback Mapped Diagnostic Contex		
	
	if (!PacmanUtils.doesAllHaveValue(severity,category,qualysApi,target,discoveredDaysRange)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}

	List<LinkedHashMap<String,Object>> issueList = new ArrayList<>();
	LinkedHashMap<String,Object> issue = new LinkedHashMap<>();
	Gson gson = new Gson();
	
	if (resourceAttributes != null && (PacmanRuleConstants.RUNNING_STATE.equalsIgnoreCase(resourceAttributes.get(PacmanRuleConstants.STATE_NAME)) || PacmanRuleConstants.RUNNING_STATE.equalsIgnoreCase(resourceAttributes.get(PacmanRuleConstants.STATUS)))) {
		String entityType = resourceAttributes.get(PacmanRuleConstants.ENTITY_TYPE);
		instanceId = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.RESOURCE_ID));
		if(PacmanUtils.calculateLaunchedDuration(firstDiscoveredOn)>Long.parseLong(discoveredDaysRange)){
		    Map<String,Object> ec2ScannesByQualysMap = new HashMap<>();
		try{
			ec2ScannesByQualysMap = PacmanUtils.checkInstanceIdFromElasticSearchForQualys(instanceId,qualysApi,"_resourceid",target);
		} catch (Exception e) {
			logger.error("unable to determine",e);
			throw new RuleExecutionFailedExeption("unable to determine"+e);
		}
		if (!ec2ScannesByQualysMap.isEmpty()) {
			annotation = Annotation.buildAnnotation(ruleParam,Annotation.Type.ISSUE);
			annotation.put(PacmanSdkConstants.DESCRIPTION,""+entityType+" instance not scanned  by qualys found!!");
			annotation.put(PacmanRuleConstants.SEVERITY, severity);
			annotation.put(PacmanRuleConstants.CATEGORY, category);
			
			issue.put(PacmanRuleConstants.VIOLATION_REASON, ""+entityType+" instance not scanned by qualys found");
			issue.put(PacmanRuleConstants.SOURCE_VERIFIED, "_resourceid,"+PacmanRuleConstants.LAST_VULN_SCAN);
			issue.put(PacmanRuleConstants.FAILED_REASON_QUALYS, gson.toJson(ec2ScannesByQualysMap));
			issueList.add(issue);
			annotation.put("issueDetails", issueList.toString());
			
			logger.debug("========ResourceScannedByQualysRule ended with annotation {} : =========" ,annotation);
			return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, annotation);
		}
	}
	}
	
	logger.debug("========ResourceScannedByQualysRule ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 17
Source File: AmazonEC2ReservedInstanceLeaseExpirationRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * @param ruleParam  
 * 
 * ************* Following are the Rule Parameters********* <br><br>
 * 
 * checkId   : Mention the checkId value <br><br>
 * 
 * ruleKey : check-for-amazon-EC2-reserved-instance-lease-expiration <br><br>
 * 
 * serviceEsURL : Enter the Es url <br><br>
 * 
 * threadsafe : if true , rule will be executed on multiple threads <br><br>
 *  
 * severity : Enter the value of severity <br><br>
 * 
 * ruleCategory : Enter the value of category <br><br>
 * 
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
 *
 */
@Override
public RuleResult execute(Map<String, String> ruleParam, Map<String, String> resourceAttributes) {
	
	logger.debug("========AmazonEC2ReservedInstanceLeaseExpirationRule started=========");
	Annotation annotation = null;
	String resourceId = null;
	String accountId = null;
	String checkId = StringUtils.trim(ruleParam.get(PacmanRuleConstants.CHECK_ID));
	
	String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
	String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
	
	String serviceEsURL = ruleParam.get(PacmanRuleConstants.ES_CHECK_SERVICE_SEARCH_URL_PARAM);
	
	MDC.put("executionId", ruleParam.get("executionId")); // this is the logback Mapped Diagnostic Contex
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); // this is the logback Mapped Diagnostic Contex
	
	List<LinkedHashMap<String,Object>>issueList = new ArrayList<>();
	LinkedHashMap<String,Object>issue = new LinkedHashMap<>();
	
	if (!PacmanUtils.doesAllHaveValue(checkId,severity,category,serviceEsURL)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}
	
	if (resourceAttributes != null) {
		accountId = resourceAttributes.get(PacmanSdkConstants.ACCOUNT_ID);
		resourceId = StringUtils.trim(resourceAttributes.get(PacmanSdkConstants.RESOURCE_ID));
		Map<String, String> amazonEc2Map = new HashMap<>();
		try {
			amazonEc2Map = PacmanUtils.getAmazonEC2ReservedInstanceLeaseExpiration(checkId,resourceId,serviceEsURL,null,accountId);
		} catch (Exception e) {
			logger.error("unable to determine",e);
			throw new RuleExecutionFailedExeption("unable to determine"+e);
		}
		if (!amazonEc2Map.isEmpty()) {
			annotation = Annotation.buildAnnotation(ruleParam, Annotation.Type.ISSUE);
			annotation.put(PacmanSdkConstants.DESCRIPTION,"Amazon EC2 Reserved instances that are scheduled to expire within the next 30 days or have expired in the preceding 30 days is found!!");
			annotation.put(PacmanRuleConstants.SEVERITY, severity);
			annotation.put(PacmanRuleConstants.CATEGORY, category);
			annotation.put(PacmanRuleConstants.EST_MONTHLY_SAVINGS, amazonEc2Map.get(PacmanRuleConstants.EST_MONTHLY_SAVINGS));
			annotation.put("instanceCount", amazonEc2Map.get("instanceCount"));
			annotation.put("reason", amazonEc2Map.get("reason"));
			
			annotation.put("status", amazonEc2Map.get("status"));
			annotation.put("platform", amazonEc2Map.get("platform"));
			annotation.put("currentMonthlyCost", amazonEc2Map.get("currentMonthlyCost"));
			annotation.put("expirationDate", amazonEc2Map.get("expirationDate"));
			annotation.put("instanceType", amazonEc2Map.get("instanceType"));
			annotation.put("zone", amazonEc2Map.get("zone"));
			
			issue.put(PacmanRuleConstants.VIOLATION_REASON, "Amazon EC2 Reserved instances that are scheduled to expire within the next 30 days or have expired in the preceding 30 days is found!!");
			issue.put(PacmanRuleConstants.CHECKID, checkId);
			issue.put(PacmanRuleConstants.SOURCE_VERIFIED, "trusted advisor");
			issueList.add(issue);
			annotation.put("issueDetails",issueList.toString());
			
			logger.debug("========AmazonEC2ReservedInstanceLeaseExpirationRule ended with an annotation {} : =========", annotation);
			return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, annotation);
		}
		}
	logger.debug("========AmazonEC2ReservedInstanceLeaseExpirationRule ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 18
Source File: OnpremScannedByQualysRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * 
 * @param ruleParam
 * 
 ************** Following are the Rule Parameters********* <br><br>
 * 
 * ruleKey : check-for-onprem-scanned-by-qualys <br><br>
 *
 * severity : Enter the value of severity <br><br>
 * 
 * esQualysUrl : Enter the Qualys URL esQualysUrl
 * 
 * ruleCategory : Enter the value of category <br><br>
 *
 *threadsafe : if true , rule will be executed on multiple threads <br><br>
 *
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
 *
 */

public RuleResult execute(final Map<String, String> ruleParam,Map<String, String> resourceAttributes) {
	logger.debug("========OnpremScannedByQualysRule started=========");
	Annotation annotation = null;
	String resourceid = null;
	String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
	String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
	String target = ruleParam.get(PacmanRuleConstants.TARGET);
	
	String qualysApi =  null;
	
	String formattedUrl = PacmanUtils.formatUrl(ruleParam,PacmanRuleConstants.ES_QUALYS_URL);
       
       if(!StringUtils.isNullOrEmpty(formattedUrl)){
           qualysApi =  formattedUrl;
       }
	
	MDC.put("executionId", ruleParam.get("executionId")); // this is the logback Mapped Diagnostic Contex
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); // this is the logback Mapped Diagnostic Contex	
	
	List<LinkedHashMap<String,Object>> issueList = new ArrayList<>();
	LinkedHashMap<String,Object> issue = new LinkedHashMap<>();
	Gson gson = new Gson();
	
	if (!PacmanUtils.doesAllHaveValue(severity,category,qualysApi,target)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}

	if (resourceAttributes != null) {
	    resourceid = StringUtils.trim(resourceAttributes.get("_resourceid"));
			Map<String,Object> onpremScannesByQualysMap = new HashMap<>();
			try {
				onpremScannesByQualysMap = PacmanUtils.checkInstanceIdFromElasticSearchForQualys(resourceid, qualysApi, "_resourceid",target);
			} catch (Exception e) {
				logger.error("unable to determine" , e);
				throw new RuleExecutionFailedExeption("unable to determine" + e);
			}
			if (!onpremScannesByQualysMap.isEmpty()) {
				annotation = Annotation.buildAnnotation(ruleParam,Annotation.Type.ISSUE);
				annotation.put(PacmanSdkConstants.DESCRIPTION,"Onprem not scanned  by qualys found!!");
				annotation.put(PacmanRuleConstants.SEVERITY, severity);
				annotation.put(PacmanRuleConstants.CATEGORY, category);
				
				issue.put(PacmanRuleConstants.VIOLATION_REASON, "Onprem asset not scanned by qualys found");
				
				issue.put(PacmanRuleConstants.SOURCE_VERIFIED, "_resourceid,"+PacmanRuleConstants.LAST_VULN_SCAN);
				issue.put(PacmanRuleConstants.FAILED_REASON_QUALYS, gson.toJson(onpremScannesByQualysMap) );
				issueList.add(issue);
				annotation.put("issueDetails", issueList.toString());
				logger.debug("========OnpremScannedByQualysRule ended with annotation {} : =========",annotation);
				return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, annotation);
			}
	}
	
	logger.debug("========OnpremScannedByQualysRule ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 19
Source File: LowUtilizationAmazonEC2InstancesRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * @param ruleParam 
 * 
 * ************* Following are the Rule Parameters********* <br><br>
 * 
 * checkId   : Mention the checkId value <br><br>
 * 
 * ruleKey : check-for-low-utilization-amazon-ec2-instance <br><br>
 * 
 * esServiceURL : Enter the Es url <br><br>
 * 
 * threadsafe : if true , rule will be executed on multiple threads <br><br>
 *  
 * severity : Enter the value of severity <br><br>
 * 
 * ruleCategory : Enter the value of category <br><br>
 * 
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
 *
 */
@Override
public RuleResult execute(Map<String, String> ruleParam, Map<String, String> resourceAttributes) {
	
	logger.debug("========LowUtilizationAmazonEC2InstancesRule started=========");
	Annotation annotation = null;
	String resourceId = null;
	String accountId = null;
	String checkId = StringUtils.trim(ruleParam.get(PacmanRuleConstants.CHECK_ID));
	
	String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
	String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
	
	String serviceEsURL = null;
	
	String pacmanHost = PacmanUtils.getPacmanHost(PacmanRuleConstants.ES_URI);
	logger.debug("========pacmanHost {}  =========",pacmanHost);
	
	if(!StringUtils.isNullOrEmpty(pacmanHost)){
	    serviceEsURL = ruleParam.get(PacmanRuleConstants.ES_CHECK_SERVICE_SEARCH_URL_PARAM);
	    serviceEsURL = pacmanHost+serviceEsURL;
	}
	
	logger.debug("========service URL after concatination param {}  =========",serviceEsURL);
	
	MDC.put("executionId", ruleParam.get("executionId")); // this is the logback Mapped Diagnostic Contex
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); // this is the logback Mapped Diagnostic Contex
	
	List<LinkedHashMap<String,Object>>issueList = new ArrayList<>();
	LinkedHashMap<String,Object>issue = new LinkedHashMap<>();
	
	if (!PacmanUtils.doesAllHaveValue(checkId,severity,category,serviceEsURL)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}
	
	if (resourceAttributes != null) {
		accountId = resourceAttributes.get(PacmanSdkConstants.ACCOUNT_ID);
		resourceId = StringUtils.trim(resourceAttributes.get(PacmanSdkConstants.RESOURCE_ID));
		Map<String, String> lowUtilEc2Map = new HashMap<>();
		try {
			lowUtilEc2Map = PacmanUtils.getLowUtilizationEc2Details(checkId,resourceId,serviceEsURL,null,accountId);
		} catch (Exception e) {
			logger.error("unable to determine",e);
			throw new RuleExecutionFailedExeption("unable to determine"+e);
		}
		if (!lowUtilEc2Map.isEmpty()) {
			annotation = Annotation.buildAnnotation(ruleParam, Annotation.Type.ISSUE);
			annotation.put(PacmanSdkConstants.DESCRIPTION,"Low utilization amazon ec2 instance found !!");
			annotation.put(PacmanRuleConstants.SEVERITY, severity); 
			annotation.put(PacmanRuleConstants.CATEGORY, category);
			annotation.put(PacmanRuleConstants.EST_MONTHLY_SAVINGS, lowUtilEc2Map.get(PacmanRuleConstants.EST_MONTHLY_SAVINGS));
			annotation.put(PacmanRuleConstants.NO_OF_LOW_UTILIZATION, lowUtilEc2Map.get(PacmanRuleConstants.NO_OF_LOW_UTILIZATION));
			
			issue.put(PacmanRuleConstants.VIOLATION_REASON, "Low utilization amazon ec2 instance found");
			issue.put(PacmanRuleConstants.CHECKID, checkId);
			issue.put(PacmanRuleConstants.SOURCE_VERIFIED, "trusted advisor");
			issueList.add(issue);
			annotation.put("issueDetails",issueList.toString());
			logger.debug("========LowUtilizationAmazonEC2InstancesRule ended with an annotation {} : =========",annotation);
			return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, annotation);
		}
		}
	logger.debug("========LowUtilizationAmazonEC2InstancesRule ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 20
Source File: ResourceWithSeverityVulnerabilityRule.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * The method will get triggered from Rule Engine with following parameters
 * 
 * @param ruleParam
 * 
 **************Following are the Rule Parameters********* <br><br>
 * 
 *  ruleKey : check-for-resource-with-severity-vulnerabilities <br><br>
 *
 *  esResourceWithVulnInfoForSeverityUrl : Enter the EC2 or vm with Vuln info ES API <br><br>
 *
 *  severityVulnValue : Enter the severity level such as S5,S4 or S3 <br><br>
 *
 * @param resourceAttributes this is a resource in context which needs to be scanned this is provided by execution engine
 *
 */

public RuleResult execute(final Map<String, String> ruleParam, Map<String, String> resourceAttributes) {
	logger.debug("========ResourcewithSeverityVulnerabilityRule started=========");
	Annotation annotation = null;
	String instanceId = null;

	String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
	String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
	String resourceWithVulnInfoForSeverityUrl = null;
	String severityVulnValue = ruleParam.get(PacmanRuleConstants.SEVERITY_VULN);
	
	String formattedUrl = PacmanUtils.formatUrl(ruleParam,PacmanRuleConstants.ES_RESOURCE_WITH_VULN_INFO_SEVERITY_URL);
       
       if(!StringUtils.isNullOrEmpty(formattedUrl)){
       	resourceWithVulnInfoForSeverityUrl =  formattedUrl;
       }

	MDC.put("executionId", ruleParam.get("executionId")); 
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID)); 
	
	List<LinkedHashMap<String,Object>>issueList = new ArrayList<>();
	LinkedHashMap<String,Object>issue = new LinkedHashMap<>();

	if (!PacmanUtils.doesAllHaveValue(resourceWithVulnInfoForSeverityUrl, severityVulnValue,severity,category)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}

	if (resourceAttributes != null) {
		String entityType = resourceAttributes.get(PacmanRuleConstants.ENTITY_TYPE);
		instanceId = StringUtils.trim(resourceAttributes.get(PacmanRuleConstants.RESOURCE_ID));
		try {
			List<String> severityList = PacmanUtils.getSeverityVulnerabilitiesByInstanceId(instanceId,resourceWithVulnInfoForSeverityUrl, severityVulnValue);
			if (!severityList.isEmpty()) {
				
				annotation = Annotation.buildAnnotation(ruleParam,Annotation.Type.ISSUE);
				annotation.put(PacmanSdkConstants.DESCRIPTION,""+entityType+" instance with vulnerability "+ severityVulnValue + " found!!");
				annotation.put(PacmanRuleConstants.SEVERITY, severity);
				annotation.put(PacmanRuleConstants.CATEGORY, category);
				
				issue.put(PacmanRuleConstants.VIOLATION_REASON, ""+entityType+" instance with vulnerability "+ severityVulnValue + " found!!");
				issue.put("voilation_title", String.join(",", severityList));
				issueList.add(issue);
				annotation.put("issueDetails",issueList.toString());
				
				logger.debug("========ResourcewithSeverityVulnerabilityRule ended with an annotation {} : =========", annotation);
				return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, annotation);

			}
		} catch (Exception e) {
			logger.error("error", e);
			throw new RuleExecutionFailedExeption(e.getMessage());
		}

	}
	logger.debug("========ResourcewithSeverityVulnerabilityRule ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}