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

The following examples show how to use com.amazonaws.util.StringUtils#isNullOrEmpty() . 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: CloudInsightSqlServer.java    From pacbot with Apache License 2.0 6 votes vote down vote up
public static Connection getDBConnection() throws SQLException {
	String hostName = getClouldInsightSqlServer();
	String dbName = "cloudinsightbillingdb";
	String user = getClouldInsightUser();
	String password = getClouldInsightPassWord();

	if (StringUtils.isNullOrEmpty(hostName) || StringUtils.isNullOrEmpty(user)
			|| StringUtils.isNullOrEmpty(password)) {
		throw new RuntimeException(
				" Cloud insight server mandatory configuration CLOUD_INSIGHT_SQL_SERVER/CLOUD_INSIGHT_USER/CLOUD_INSIGHT_PASSWORD ");
	}
	String url = String.format(
			"jdbc:sqlserver://%s:1433;database=%s;user=%s;password=%s;encrypt=true;"
					+ "hostNameInCertificate=*.database.windows.net;loginTimeout=30;",
			hostName, dbName, user, password);
	Connection connection = null;

	connection = DriverManager.getConnection(url);
	return connection;
}
 
Example 3
Source File: RepositoryS3.java    From github-bucket with ISC License 6 votes vote down vote up
private boolean isUploadFile(Iterator<S3ObjectSummary> iter, String path, String hash) {
    while (iter.hasNext()) {
        S3ObjectSummary fileS3 = iter.next();
        // Filename should look like this:
        // a/b
        if (!fileS3.getKey().equals(path)) {
            // If this is another file, then continue!
            continue;
        }
        // Remove the file from the S3 list as it does not need to be processed further
        iter.remove();
        // Upload if the hashes differ
        return StringUtils.isNullOrEmpty(hash) || !fileS3.getETag().equals(hash);
    }
    return true;
}
 
Example 4
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
private void withFederatedUserId(@Nonnull EnvVars localEnv) {
	if (!StringUtils.isNullOrEmpty(this.step.getFederatedUserId())) {
		AWSSecurityTokenService sts = AWSClientFactory.create(AWSSecurityTokenServiceClientBuilder.standard(), this.envVars);
		GetFederationTokenRequest getFederationTokenRequest = new GetFederationTokenRequest();
		getFederationTokenRequest.setDurationSeconds(this.step.getDuration());
		getFederationTokenRequest.setName(this.step.getFederatedUserId());
		getFederationTokenRequest.setPolicy(ALLOW_ALL_POLICY);

		GetFederationTokenResult federationTokenResult = sts.getFederationToken(getFederationTokenRequest);

		Credentials credentials = federationTokenResult.getCredentials();
		localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, credentials.getAccessKeyId());
		localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, credentials.getSecretAccessKey());
		localEnv.override(AWSClientFactory.AWS_SESSION_TOKEN, credentials.getSessionToken());
		this.envVars.overrideAll(localEnv);
	}

}
 
Example 5
Source File: RepositoryS3.java    From github-bucket with ISC License 6 votes vote down vote up
private boolean isUploadFile(Iterator<S3ObjectSummary> iter, String path, String hash) {
    while (iter.hasNext()) {
        S3ObjectSummary fileS3 = iter.next();
        // Filename should look like this:
        // a/b
        if (!fileS3.getKey().equals(path)) {
            // If this is another file, then continue!
            continue;
        }
        // Remove the file from the S3 list as it does not need to be processed further
        iter.remove();
        // Upload if the hashes differ
        return StringUtils.isNullOrEmpty(hash) || !fileS3.getETag().equals(hash);
    }
    return true;
}
 
Example 6
Source File: AlexaClient.java    From alexa-skills-kit-tester-java with Apache License 2.0 5 votes vote down vote up
AlexaClient(final AlexaClientBuilder builder) {
    this.millisFromCurrentDate = builder.timestamp.getTime() - new Date().getTime();
    this.locale = builder.locale;
    apiEndpoint = apiEndpoints.getOrDefault(builder.apiEndpoint, apiEndpoints.get(NA));
    this.application = new Application(builder.applicationId);
    this.user = User.builder().withUserId(builder.uid).withAccessToken(builder.accessToken).build();
    this.device = builder.device;
    this.debugFlagSessionAttributeName = StringUtils.isNullOrEmpty(builder.debugFlagSessionAttributeName) ? Optional.empty() : Optional.of(builder.debugFlagSessionAttributeName);
    this.endpoint = builder.endpoint;
    this.yLaunch = builder.yLaunch;
}
 
Example 7
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private String createAccountId(final AWSSecurityTokenService sts) {
	if (!StringUtils.isNullOrEmpty(this.step.getRoleAccount())) {
		return this.step.getRoleAccount();
	} else {
		return sts.getCallerIdentity(new GetCallerIdentityRequest()).getAccount();
	}
}
 
Example 8
Source File: DefaultFileHelper.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private String getUniqueDateWithIncrementalFileName(String keyPrefix) {
  fileCount++;
  StringBuilder fileName = new StringBuilder();
  fileName.append(keyPrefix).append(fileCount);

  if (!StringUtils.isNullOrEmpty(s3TargetConfigBean.fileNameSuffix)) {
    fileName.append(DOT);
    fileName.append(s3TargetConfigBean.fileNameSuffix);
  }

  if (s3TargetConfigBean.compress) {
    fileName.append(GZIP_EXTENSION);
  }
  return fileName.toString();
}
 
Example 9
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private void withCredentials(@Nonnull Run<?, ?> run, @Nonnull EnvVars localEnv) throws IOException, InterruptedException {
	if (!StringUtils.isNullOrEmpty(this.step.getCredentials())) {
		StandardUsernamePasswordCredentials usernamePasswordCredentials = CredentialsProvider.findCredentialById(this.step.getCredentials(),
				StandardUsernamePasswordCredentials.class, run, Collections.emptyList());

		AmazonWebServicesCredentials amazonWebServicesCredentials = CredentialsProvider.findCredentialById(this.step.getCredentials(),
				AmazonWebServicesCredentials.class, run, Collections.emptyList());
		if (usernamePasswordCredentials != null) {
			localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, usernamePasswordCredentials.getUsername());
			localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, usernamePasswordCredentials.getPassword().getPlainText());
		} else if (amazonWebServicesCredentials != null) {
			AWSCredentials awsCredentials;

			if (StringUtils.isNullOrEmpty(this.step.getIamMfaToken())) {
				this.getContext().get(TaskListener.class).getLogger().format("Constructing AWS Credentials");
				awsCredentials = amazonWebServicesCredentials.getCredentials();
			} else {
				// Since the getCredentials does its own roleAssumption, this is all it takes to get credentials
				// with this token.
				this.getContext().get(TaskListener.class).getLogger().format("Constructing AWS Credentials utilizing MFA Token");
				awsCredentials = amazonWebServicesCredentials.getCredentials(this.step.getIamMfaToken());
				BasicSessionCredentials basicSessionCredentials = (BasicSessionCredentials) awsCredentials;
				localEnv.override(AWSClientFactory.AWS_SESSION_TOKEN, basicSessionCredentials.getSessionToken());
			}

			localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, awsCredentials.getAWSAccessKeyId());
			localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, awsCredentials.getAWSSecretKey());
		} else {
			throw new RuntimeException("Cannot find a Username with password credential with the ID " + this.step.getCredentials());
		}
	} else if (!StringUtils.isNullOrEmpty(this.step.getSamlAssertion())) {
		localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, "access_key_not_used_will_pass_through_SAML_assertion");
		localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, "secret_access_key_not_used_will_pass_through_SAML_assertion");
	}
	this.envVars.overrideAll(localEnv);
}
 
Example 10
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private String createRoleSessionName() {
	if (StringUtils.isNullOrEmpty(this.step.roleSessionName)) {
		return RoleSessionNameBuilder
				.withJobName(this.envVars.get("JOB_NAME"))
				.withBuildNumber(this.envVars.get("BUILD_NUMBER"))
				.build();
	} else {
		return this.step.roleSessionName;
	}
}
 
Example 11
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 12
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 13
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 14
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);
}
 
Example 15
Source File: Branch.java    From github-bucket with ISC License 4 votes vote down vote up
public Branch(String branch) {
    if (StringUtils.isNullOrEmpty(branch)) {
        throw new IllegalArgumentException();
    }
    this.branch = branch.startsWith(Constants.R_HEADS) ? branch.substring(Constants.R_HEADS.length()) : branch;
}
 
Example 16
Source File: UnusedSgAutoFix.java    From pacbot with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isFixCandidate(String resourceId, String resourceType, Map<String, Object> clientMap, Map<String, String> ruleParams, Map<String, String> issue) throws AutoFixException {
	String groupName = issue.get("groupname");
	return !StringUtils.isNullOrEmpty(groupName) && groupName.startsWith(PacmanSdkConstants.PACBOT_CREATED_SG_DESC);
}
 
Example 17
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 18
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 19
Source File: S3AccessLogsRule.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-s3-access-logs<br><br>
 *
 *esS3PubAccessIssueUrl : Enter the S3 Public Access ES issue URL <br><br>
 *
 *s3PublicAccessRuleId : Enter the ruleId which is s3 with public access with read\write<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("========S3AccessLogsRule started=========");
	Annotation annotation = null;
	String esS3PubAccessIssueUrl = null;
	List<LinkedHashMap<String, Object>> issueList = new ArrayList<>();
	LinkedHashMap<String, Object> issue = new LinkedHashMap<>();
	String s3Bucket = ruleParam.get(PacmanRuleConstants.RESOURCE_ID);
	String destinationBucketForAutoFix = ruleParam.get(PacmanRuleConstants.DESTINATION_BUCKET_AUTOFIX);
	String accessLogsEnabledRegions = ruleParam.get(PacmanRuleConstants.ACCESSLOGS_ENABLED_REGIONS);
	String splitter = ruleParam.get(PacmanSdkConstants.SPLITTER_CHAR);
	String region = resourceAttributes.get(PacmanRuleConstants.REGION_ATTR);
	String accountId = resourceAttributes.get(PacmanRuleConstants.ACCOUNTID);
	String targetType = resourceAttributes.get(PacmanRuleConstants.ENTITY_TYPE);
	String isLoggingEnabled = resourceAttributes.get(PacmanRuleConstants.IS_S3_ACCESS_LOGS_ENABLED);

	String description = targetType+ " has not enabled the server access logs for " + s3Bucket;
	String s3PublicAccessRuleId = ruleParam.get(PacmanRuleConstants.S3_PUBLIC_ACCESS_RULE_ID);
       Map<String, String> data = new HashMap<>();
       data.put("ACCOUNT_ID", accountId);
       data.put("REGION", region);
       destinationBucketForAutoFix = StrSubstitutor.replace(destinationBucketForAutoFix, data);

	String pacmanHost = PacmanUtils.getPacmanHost(PacmanRuleConstants.ES_URI);
	logger.debug("========pacmanHost {}  =========", pacmanHost);

	if (!StringUtils.isNullOrEmpty(pacmanHost)) {
		esS3PubAccessIssueUrl = ruleParam.get(PacmanRuleConstants.ES_S3_PUBLIC_ACCESS_ISSUE_URL);
		esS3PubAccessIssueUrl = pacmanHost + esS3PubAccessIssueUrl;
	}

	MDC.put("executionId", ruleParam.get("executionId"));
	MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID));

	if (!PacmanUtils.doesAllHaveValue(esS3PubAccessIssueUrl,s3PublicAccessRuleId,destinationBucketForAutoFix,accessLogsEnabledRegions,splitter)) {
		logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
		throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
	}
	try {

		Map<String, Object> mustFilter = new HashMap<>();
		mustFilter.put(PacmanRuleConstants.RESOURCE_ID, s3Bucket);
		mustFilter.put(PacmanRuleConstants.RULE_ID, s3PublicAccessRuleId);
		mustFilter.put(PacmanRuleConstants.ACCOUNTID, accountId);
		mustFilter.put(PacmanRuleConstants.REGION_ATTR, region);
		HashMultimap<String, Object> shouldFilter = HashMultimap.create();
		Map<String, Object> mustTermsFilter = new HashMap<>();
		shouldFilter.put(PacmanSdkConstants.ISSUE_STATUS_KEY,PacmanSdkConstants.STATUS_OPEN);
		shouldFilter.put(PacmanSdkConstants.ISSUE_STATUS_KEY,PacmanRuleConstants.STATUS_EXEMPTED);

		Set<String> resourceSet = PacmanUtils.getValueFromElasticSearchAsSet(esS3PubAccessIssueUrl,mustFilter, shouldFilter, mustTermsFilter,"_resourceid", null);
			logger.debug("======issueDetails : {}", resourceSet);	
		
			logger.debug("======isLoggingEnabled : {}", Boolean.parseBoolean(isLoggingEnabled));	
		
		if (resourceSet.isEmpty() && !Boolean.parseBoolean(isLoggingEnabled)) {
			String destinationBucketName = resourceAttributes.get(PacmanRuleConstants.DESTINATION_BUCKET_NAME);
			String logFilePrefix = resourceAttributes.get(PacmanRuleConstants.LOG_FILE_PREFIX);
			annotation = Annotation.buildAnnotation(ruleParam,Annotation.Type.ISSUE);
			annotation.put(PacmanSdkConstants.DESCRIPTION, description);
			annotation.put(PacmanRuleConstants.SEVERITY,ruleParam.get(PacmanRuleConstants.SEVERITY));
			annotation.put(PacmanRuleConstants.CATEGORY,ruleParam.get(PacmanRuleConstants.CATEGORY));
			destinationBucketForAutoFix = destinationBucketForAutoFix.replace("ACCOUNT_ID", accountId);
			destinationBucketForAutoFix = destinationBucketForAutoFix.replace("REGION", region);
			annotation.put(PacmanRuleConstants.DESTINATION_BUCKET_AUTOFIX,destinationBucketForAutoFix);
			annotation.put(PacmanRuleConstants.ACCESSLOGS_ENABLED_REGIONS,accessLogsEnabledRegions);
			annotation.put(PacmanSdkConstants.SPLITTER_CHAR,splitter);
			issue.put(PacmanRuleConstants.VIOLATION_REASON, description);
			issue.put(PacmanRuleConstants.IS_S3_ACCESS_LOGS_ENABLED, isLoggingEnabled);
			issue.put(PacmanRuleConstants.DESTINATION_BUCKET_NAME, destinationBucketName);
			issue.put(PacmanRuleConstants.LOG_FILE_PREFIX, logFilePrefix);
			issueList.add(issue);
			annotation.put("issueDetails", issueList.toString());
			logger.debug("========S3AccessLogsRule ended with an annotation {} : =========",annotation);
			return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,PacmanRuleConstants.FAILURE_MESSAGE, annotation);
		}
	} catch (Exception e) {
		logger.error(e.getMessage());
		throw new RuleExecutionFailedExeption(e.getMessage());
	}
	logger.debug("========S3AccessLogsRule ended=========");
	return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,PacmanRuleConstants.SUCCESS_MESSAGE);
}
 
Example 20
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);
}