com.amazonaws.services.ec2.model.GroupIdentifier Java Examples

The following examples show how to use com.amazonaws.services.ec2.model.GroupIdentifier. 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: PacmanEc2UtilsTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("static-access")
@Test
public void checkAccessibleToAllTest() throws Exception {
    GroupIdentifier identifier = new GroupIdentifier();
    identifier.setGroupId("sg-5414b52c");
    Set<GroupIdentifier> secuityGroups = new HashSet<GroupIdentifier>();
    secuityGroups.add(identifier);
    mockStatic(PacmanUtils.class);
    when(PacmanUtils.doHttpPost(anyString(),anyString())).thenReturn("{\"took\":67,\"timed_out\":false,\"_shards\":{\"total\":3,\"successful\":3,\"failed\":0},\"hits\":{\"total\":1,\"max_score\":12.365102,\"hits\":[{\"_index\":\"_index\",\"_type\":\"_type\",\"_id\":\"_id\",\"_score\":12.365102,\"_routing\":\"_routing\",\"_parent\":\"_parent\",\"_source\":{\"discoverydate\":\"2018-07-31 08:00:00+00\",\"accountid\":\"accountid\",\"region\":\"region\",\"groupid\":\"groupid\",\"type\":\"inbound\",\"ipprotocol\":\"tcp\",\"fromport\":\"80\",\"toport\":\"80\",\"cidrip\":\"0.0.0.0\0\",\"cidripv6\":\"\",\"accountname\":\"accountname\",\"_loaddate\":\"2018-07-31 9:24:00+0000\"}}]}}");
    
    assertThat(pacmanEc2Utils.checkAccessibleToAll(secuityGroups,"11","url","describeFlowLogsRequest"),is(notNullValue()));
    
    when(PacmanUtils.doHttpPost(anyString(),anyString())).thenThrow(new RuleExecutionFailedExeption());
    assertThatThrownBy( 
            () -> pacmanEc2Utils.checkAccessibleToAll(secuityGroups,"11","url","describeFlowLogsRequest")).isInstanceOf(RuleExecutionFailedExeption.class);
}
 
Example #2
Source File: Ec2GlobalAccessFix.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@Override
public boolean backupExistingConfigForResource(final String resourceId, final String resourceType, Map<String, Object> clientMap, Map<String, String> ruleParams, Map<String, String> issue) throws AutoFixException {
	StringBuilder oldConfig = new StringBuilder();
	Instance instance;
	try {
		instance = PublicAccessAutoFix.getInstanceDetailsForEc2(clientMap,resourceId);

		List<GroupIdentifier> originalSg = instance.getSecurityGroups();

		for (GroupIdentifier sgm : originalSg) {
			if (oldConfig.length() > 0) {
				oldConfig.append(",").append(sgm.getGroupId());
			} else {
				oldConfig.append(sgm.getGroupId());
			}
		}
	} catch (Exception e) {
		LOGGER.error("back up failed", e.getMessage());
		throw new AutoFixException("backup failed");
	}
	DETACHED_SG = oldConfig.toString();
	 backupOldConfig(resourceId, EXISTING_GROUPS, oldConfig.toString());
        LOGGER.debug("backup complete for {}" , resourceId);
        return true;
}
 
Example #3
Source File: EC2PublicAccessForConfiguredPortRule.java    From pacbot with Apache License 2.0 6 votes vote down vote up
private Annotation createAnnotation(Map<String, String> resourceAttributes, Set<GroupIdentifier> securityGroupsSet, Map<String, String> ruleParam, List<LinkedHashMap<String, Object>> issueList, LinkedHashMap<String, Object> issue, String sgRulesUrl) {
    Annotation annotation = null;
    try {
        Map<String, Boolean> sgOpen = PacmanUtils.checkAccessibleToAll(securityGroupsSet,ruleParam.get(PacmanRuleConstants.PORT_TO_CHECK), sgRulesUrl, ruleParam.get(PacmanRuleConstants.CIDR_IP),"::/0","");

        if (!sgOpen.isEmpty()) {
            annotation = Annotation.buildAnnotation(ruleParam, Annotation.Type.ISSUE);
            annotation.put(PacmanSdkConstants.DESCRIPTION,"EC2 has port : " + ruleParam.get(PacmanRuleConstants.PORT_TO_CHECK) + " publicly open");
            issue.put(PacmanRuleConstants.VIOLATION_REASON,"ResourceId " + ruleParam.get(PacmanSdkConstants.RESOURCE_ID)+ " has public access through port " + ruleParam.get(PacmanRuleConstants.PORT_TO_CHECK));
            issue.put(PacmanRuleConstants.PORTS_VIOLATED, ruleParam.get(PacmanRuleConstants.PORT_TO_CHECK));
            issueList.add(issue);
            annotation.put("issueDetails", issueList.toString());
            annotation.put("EC2PublicIP", resourceAttributes.get(PacmanRuleConstants.PUBLIC_IP_ADDR));
            annotation.put(PacmanRuleConstants.SEVERITY, ruleParam.get(PacmanRuleConstants.SEVERITY));
            annotation.put(PacmanRuleConstants.CATEGORY, ruleParam.get(PacmanRuleConstants.CATEGORY));
            annotation.put(PacmanRuleConstants.VPC_ID, resourceAttributes.get(PacmanRuleConstants.VPC_ID));
            annotation.put(PacmanRuleConstants.SUBNETID, resourceAttributes.get(PacmanRuleConstants.SUBNETID));
            logger.debug("========EC2PublicAccessForConfiguredPortRule ended with an annotation {} : =========", annotation);
        }
    } catch (Exception e) {
        logger.error(e.getMessage());
        throw new RuleExecutionFailedExeption(e.getMessage());
    }
    return annotation;
}
 
Example #4
Source File: PacmanUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
public static List<GroupIdentifier> getSecurityGroupsByInstanceId(String instanceId, String esUrl) throws Exception {
    List<GroupIdentifier> list = new ArrayList<>();
    JsonParser jsonParser = new JsonParser();
    Map<String, Object> mustFilter = new HashMap<>();
    Map<String, Object> mustNotFilter = new HashMap<>();
    HashMultimap<String, Object> shouldFilter = HashMultimap.create();
    Map<String, Object> mustTermsFilter = new HashMap<>();
    mustFilter.put(convertAttributetoKeyword(PacmanRuleConstants.INSTANCEID), instanceId);
    JsonObject resultJson = RulesElasticSearchRepositoryUtil.getQueryDetailsFromES(esUrl, mustFilter,
            mustNotFilter, shouldFilter, null, 0, mustTermsFilter, null,null);
    if (resultJson != null && resultJson.has(PacmanRuleConstants.HITS)) {
        JsonObject hitsJson = (JsonObject) jsonParser.parse(resultJson.get(PacmanRuleConstants.HITS).toString());
        JsonArray hitsArray = hitsJson.getAsJsonArray(PacmanRuleConstants.HITS);
        for (int i = 0; i < hitsArray.size(); i++) {
            JsonObject source = hitsArray.get(i).getAsJsonObject().get(PacmanRuleConstants.SOURCE)
                    .getAsJsonObject();
            String securitygroupid = source.get(PacmanRuleConstants.EC2_WITH_SECURITYGROUP_ID).getAsString();
            GroupIdentifier groupIdentifier = new GroupIdentifier();
            if (!com.amazonaws.util.StringUtils.isNullOrEmpty(securitygroupid)) {
                groupIdentifier.setGroupId(securitygroupid);
                list.add(groupIdentifier);
            }
        }
    }
    return list;
}
 
Example #5
Source File: PacmanUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Check accessible to all.
 *
 * @param secuityGroups the secuity groups
 * @param portToCheck the port to check
 * @param sgRulesUrl the sg rules url
 * @param cidrIp the cidr ip
 * @param cidripv6 the cidripv 6
 * @param target the target
 * @return the map
 * @throws Exception the exception
 */
public static Map<String, Boolean> checkAccessibleToAll(Set<GroupIdentifier> secuityGroups, String portToCheck,
        String sgRulesUrl, String cidrIp, String cidripv6,String target) throws Exception {
    JsonObject resultJsonCidrip = null;
    LinkedHashMap<String, Boolean> openPorts = new LinkedHashMap<>();
    for (GroupIdentifier securityGrp : secuityGroups) {
        Map<String, Object> mustFilter = new HashMap<>();
        Map<String, Object> mustNotFilter = new HashMap<>();
        HashMultimap<String, Object> shouldFilter = HashMultimap.create();
        Map<String, Object> mustTermsFilter = new HashMap<>();
        mustFilter.put(convertAttributetoKeyword(PacmanRuleConstants.GROUP_ID), securityGrp.getGroupId());
        shouldFilter.put(convertAttributetoKeyword(PacmanRuleConstants.CIDRIP), cidrIp);
        shouldFilter.put(convertAttributetoKeyword(PacmanRuleConstants.CIDRIPV6), cidripv6);
        mustFilter.put(convertAttributetoKeyword(PacmanSdkConstants.TYPE), PacmanRuleConstants.INBOUND);
        resultJsonCidrip = RulesElasticSearchRepositoryUtil.getQueryDetailsFromES(sgRulesUrl, mustFilter,
                mustNotFilter, shouldFilter, null, 0, mustTermsFilter, null,null);
        proccessCidrIpOrCidrIpv6Data(resultJsonCidrip, portToCheck, openPorts,target);
    }

    return openPorts;
}
 
Example #6
Source File: PacmanUtils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the security grouplist.
 *
 * @param securityGroupId the security group id
 * @param delimeter the delimeter
 * @param securityGrouplist the security grouplist
 * @return the security grouplist
 */
public static List<GroupIdentifier> getSecurityGrouplist(String securityGroupId, String delimeter,
        List<GroupIdentifier> securityGrouplist) {
    List<String> sgList = new ArrayList(Arrays.asList(securityGroupId.split(delimeter)));
    for (String sg : sgList) {
        GroupIdentifier groupIdentifier = new GroupIdentifier();
        groupIdentifier.setGroupId(sg);
        securityGrouplist.add(groupIdentifier);
    }
    return securityGrouplist;
}
 
Example #7
Source File: Ec2DaoImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the security groups to an EC2 instance.
 *
 * @param ec2InstanceId the ec2 instance id.
 * @param securityGroups security groups to be added.
 * @param awsParams awsParamsDto object
 *
 * @return updated security groups.
 */
@Override
public List<String> addSecurityGroupsToEc2Instance(String ec2InstanceId, List<String> securityGroups, AwsParamsDto awsParams)
{
    Set<String> updatedSecurityGroups = new HashSet<>();
    for (String securityGroup : securityGroups)
    {
        updatedSecurityGroups.add(securityGroup);
    }

    // Get existing security groups
    DescribeInstanceAttributeRequest describeInstanceAttributeRequest =
        new DescribeInstanceAttributeRequest().withInstanceId(ec2InstanceId).withAttribute(InstanceAttributeName.GroupSet);

    DescribeInstanceAttributeResult describeInstanceAttributeResult =
        ec2Operations.describeInstanceAttribute(getEc2Client(awsParams), describeInstanceAttributeRequest);

    List<GroupIdentifier> groups = describeInstanceAttributeResult.getInstanceAttribute().getGroups();
    for (GroupIdentifier groupIdentifier : groups)
    {
        updatedSecurityGroups.add(groupIdentifier.getGroupId());
    }

    // Add security group on master EC2 instance
    ModifyInstanceAttributeRequest modifyInstanceAttributeRequest =
        new ModifyInstanceAttributeRequest().withInstanceId(ec2InstanceId).withGroups(updatedSecurityGroups);

    ec2Operations.modifyInstanceAttribute(getEc2Client(awsParams), modifyInstanceAttributeRequest);

    return new ArrayList<>(updatedSecurityGroups);
}
 
Example #8
Source File: MockEc2OperationsImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public DescribeInstanceAttributeResult describeInstanceAttribute(AmazonEC2Client ec2Client,
    DescribeInstanceAttributeRequest describeInstanceAttributeRequest)
{
    InstanceAttribute instanceAttribute = new InstanceAttribute();
    instanceAttribute.withGroups(new GroupIdentifier().withGroupId("A_TEST_SECURITY_GROUP"));
    return new DescribeInstanceAttributeResult().withInstanceAttribute(instanceAttribute);
}
 
Example #9
Source File: PacmanUtils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
   * Gets the query from elastic search.
   *
   * @param securityGroupId the security group id
   * @param serviceWithSgEsUrl the service with sg es url
   * @param esUrlParam the es url param
   * @param ruleParams the rule params
   * @return the query from elastic search
   * @throws Exception the exception
   */
  public static String getQueryFromElasticSearch(String securityGroupId,
          List<String> serviceWithSgEsUrl, String esUrlParam,Map<String,String> ruleParams) throws Exception {
      String securityGroupAttribute = null;
      String servicesWithSgurl = null;
      String returnedValue = null;
      String latest = "";
      for (String esUrl : serviceWithSgEsUrl) {
          servicesWithSgurl = esUrlParam + esUrl;
          if (esUrl.contains("ec2") || esUrl.contains("lambda") || esUrl.contains("appelb")
                  || esUrl.contains("classicelb") || esUrl.contains("elasticsearch")) {
              securityGroupAttribute = PacmanRuleConstants.EC2_WITH_SECURITYGROUP_ID;
              if(esUrl.contains("elasticsearch")){
              	latest = "true";
              }
          } else {
              securityGroupAttribute = PacmanRuleConstants.SECURITYGROUP_ID_ATTRIBUTE;
          }
          Map<String, List<String>> matchPhrase = new HashMap<>();
          
          List<String> ids = new ArrayList<>();
          ids.add(securityGroupId);
          matchPhrase.put(securityGroupAttribute, ids);
          	 returnedValue =  getValueFromElasticSearch(ruleParams.get("accountid"),"", servicesWithSgurl, securityGroupAttribute, ruleParams.get("region"), securityGroupAttribute, latest,matchPhrase);
	if (!StringUtils.isEmpty(returnedValue)) {
		List<GroupIdentifier> listSecurityGroupID = new ArrayList<>();
		getSecurityGrouplist(returnedValue, ":;", listSecurityGroupID);
		for(GroupIdentifier sgId:listSecurityGroupID){
			if(sgId.getGroupId().equals(securityGroupId)){
				return securityGroupId;
			}
		}
		
	}
         
      }
return returnedValue;
  }
 
Example #10
Source File: PacmanUtils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the security groups by resource id.
 *
 * @param resourceId the resourceId
 * @param esUrl the es url
 * @param resourceField the resource field
 * @param sgField the sgField
 * @param sgStatusField the sgStatusField
 * @return the security groups by resource id
 * @throws Exception the exception
 */
public static List<GroupIdentifier> getSecurityGroupsByResourceId(String resourceId, String esUrl,String resourceField,String sgField,String sgStatusField) throws Exception {
    List<GroupIdentifier> list = new ArrayList<>();
    JsonParser jsonParser = new JsonParser();
    Map<String, Object> mustFilter = new HashMap<>();
    Map<String, Object> mustNotFilter = new HashMap<>();
    HashMultimap<String, Object> shouldFilter = HashMultimap.create();
    Map<String, Object> mustTermsFilter = new HashMap<>();
    mustFilter.put(convertAttributetoKeyword(resourceField), resourceId);
    JsonObject resultJson = RulesElasticSearchRepositoryUtil.getQueryDetailsFromES(esUrl, mustFilter,
            mustNotFilter, shouldFilter, null, 0, mustTermsFilter, null,null);
    if (resultJson != null && resultJson.has(PacmanRuleConstants.HITS)) {
        JsonObject hitsJson = (JsonObject) jsonParser.parse(resultJson.get(PacmanRuleConstants.HITS).toString());
        JsonArray hitsArray = hitsJson.getAsJsonArray(PacmanRuleConstants.HITS);
        for (int i = 0; i < hitsArray.size(); i++) {
            JsonObject source = hitsArray.get(i).getAsJsonObject().get(PacmanRuleConstants.SOURCE)
                    .getAsJsonObject();
            String securitygroupid = source.get(sgField).getAsString();
            String vpcSecuritygroupStatus = source.get(sgStatusField).getAsString();
            if("active".equals(vpcSecuritygroupStatus)){
            GroupIdentifier groupIdentifier = new GroupIdentifier();
            if (!com.amazonaws.util.StringUtils.isNullOrEmpty(securitygroupid)) {
                groupIdentifier.setGroupId(securitygroupid);
                list.add(groupIdentifier);
            }
        }
        }
    }
    return list;
}
 
Example #11
Source File: PacmanUtils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the security broup id by elb.
 *
 * @param resourceId the resource id
 * @param elbSecurityApi the elb security api
 * @param accountId the account id
 * @param region the region
 * @return the security broup id by elb
 * @throws Exception the exception
 */
public static List<GroupIdentifier> getSecurityBroupIdByElb(String resourceId, String elbSecurityApi,
        String accountId, String region) throws Exception {
    JsonArray hits;
    JsonParser parser = new JsonParser();
    String securityGroupId = null;
    List<GroupIdentifier> securityGrouplist = new ArrayList<>();
    Map<String, Object> mustFilter = new HashMap<>();
    Map<String, Object> mustNotFilter = new HashMap<>();
    HashMultimap<String, Object> shouldFilter = HashMultimap.create();
    Map<String, Object> mustTermsFilter = new HashMap<>();
    mustFilter.put(convertAttributetoKeyword(PacmanRuleConstants.LOAD_BALANCER_ID_ATTRIBUTE), resourceId);
    mustFilter.put(convertAttributetoKeyword(PacmanRuleConstants.ACCOUNTID), accountId);
    mustFilter.put(convertAttributetoKeyword(PacmanRuleConstants.REGION_ATTR), region);
    JsonObject resultJson = RulesElasticSearchRepositoryUtil.getQueryDetailsFromES(elbSecurityApi, mustFilter,
            mustNotFilter, shouldFilter, null, 0, mustTermsFilter, null,null);
    if (null != resultJson && resultJson.has(PacmanRuleConstants.HITS)) {
        String hitsJsonString = resultJson.get(PacmanRuleConstants.HITS).toString();
        JsonObject hitsJson = (JsonObject) parser.parse(hitsJsonString);
        hits = hitsJson.getAsJsonObject().get(PacmanRuleConstants.HITS).getAsJsonArray();
        if (hits.size() > 0) {
            JsonObject firstObject = (JsonObject) hits.get(0);
            JsonObject sourceJson = (JsonObject) firstObject.get(PacmanRuleConstants.SOURCE);
            if (null != sourceJson && sourceJson.has(PacmanRuleConstants.EC2_WITH_SECURITYGROUP_ID)) {
                securityGroupId = sourceJson.get(PacmanRuleConstants.EC2_WITH_SECURITYGROUP_ID).getAsString();
                getSecurityGrouplist(securityGroupId, ":;", securityGrouplist);
            }
        }
    }
    return securityGrouplist;
}
 
Example #12
Source File: CommonTestUtils.java    From pacbot with Apache License 2.0 4 votes vote down vote up
public static Set<GroupIdentifier> getSetGroupIdentifier(String passRuleResourceId) {
    Set<GroupIdentifier> commonSet = new HashSet<>();
    commonSet.add(getGroupIdentifier(passRuleResourceId));
    return commonSet;
}
 
Example #13
Source File: AWSReservation.java    From sequenceiq-samples with Apache License 2.0 4 votes vote down vote up
public List<GroupIdentifier> getGroups() {
	return groups;
}
 
Example #14
Source File: AWSReservation.java    From sequenceiq-samples with Apache License 2.0 4 votes vote down vote up
public void setGroups(List<GroupIdentifier> groups) {
	this.groups = groups;
}
 
Example #15
Source File: NetworkInterfaceImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public List<GroupIdentifier> getGroups() {
    return (List<GroupIdentifier>) resource.getAttribute("Groups");
}
 
Example #16
Source File: FetchEC2Job.java    From fullstop with Apache License 2.0 4 votes vote down vote up
private void processInstance(String account, String region, Instance instance) {
    final Map<String, Object> metaData = newHashMap();
    metaData.putAll(amiDetailsProvider.getAmiDetails(account, getRegion(fromName(region)), instance.getImageId()));
    final List<String> errorMessages = newArrayList();
    final String instancePublicIpAddress = instance.getPublicIpAddress();

    if (violationService.violationExists(account, region, EVENT_ID, instance.getInstanceId(), UNSECURED_PUBLIC_ENDPOINT)) {
        return;
    }

    final Map<String, SecurityGroupCheckDetails> unsecureGroups = securityGroupsChecker.check(
            instance.getSecurityGroups().stream().map(GroupIdentifier::getGroupId).collect(toList()),
            account,
            getRegion(fromName(region)));
    if (!unsecureGroups.isEmpty()) {
        metaData.put("unsecuredSecurityGroups", unsecureGroups);
        errorMessages.add("Unsecured security group! Only ports 80 and 443 are allowed");
    }

    if (errorMessages.size() > 0) {
        metaData.put("errorMessages", errorMessages);
        writeViolation(account, region, metaData, instance.getInstanceId());

        // skip http response check, as we are already having a violation here
        return;
    }

    // skip check for publicly available apps
    if (awsApplications.isPubliclyAccessible(account, region, newArrayList(instance.getInstanceId())).orElse(false)) {
        return;
    }

    for (final Integer allowedPort : jobsProperties.getEc2AllowedPorts()) {

        if (allowedPort == 22) {
            continue;
        }

        final HttpGetRootCall httpCall = new HttpGetRootCall(httpClient, instancePublicIpAddress, allowedPort);
        final ListenableFuture<HttpCallResult> listenableFuture = threadPoolTaskExecutor.submitListenable(
                httpCall);
        listenableFuture.addCallback(
                httpCallResult -> {
                    log.debug("address: {} and port: {}", instancePublicIpAddress, allowedPort);
                    if (httpCallResult.isOpen()) {
                        final Map<String, Object> md = ImmutableMap.<String, Object>builder()
                                .putAll(metaData)
                                .put("instancePublicIpAddress", instancePublicIpAddress)
                                .put("Port", allowedPort)
                                .put("Error", httpCallResult.getMessage()).build();
                        writeViolation(account, region, md, instance.getInstanceId());
                    }
                }, ex -> log.warn("Could not call " + instancePublicIpAddress, ex));

        log.debug("Active threads in pool: {}/{}", threadPoolTaskExecutor.getActiveCount(), threadPoolTaskExecutor.getMaxPoolSize());
    }
}
 
Example #17
Source File: InstanceImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public List<GroupIdentifier> getSecurityGroups() {
    return (List<GroupIdentifier>) resource.getAttribute("SecurityGroups");
}
 
Example #18
Source File: EC2Instance.java    From billow with Apache License 2.0 4 votes vote down vote up
public EC2Instance(Instance instance) {
    this.id = instance.getInstanceId();
    this.type = instance.getInstanceType();
    this.lifecycle = instance.getInstanceLifecycle();
    this.hypervisor = instance.getHypervisor();
    this.az = instance.getPlacement().getAvailabilityZone();
    this.group = instance.getPlacement().getGroupName();
    this.tenancy = instance.getPlacement().getTenancy();
    this.vpc = instance.getVpcId();
    this.platform = instance.getPlatform();
    this.kernel = instance.getKernelId();
    this.key = instance.getKeyName();
    this.image = instance.getImageId();
    this.privateIP = instance.getPrivateIpAddress();
    this.publicIP = instance.getPublicIpAddress();
    this.publicHostname = instance.getPublicDnsName();
    this.privateHostname = instance.getPrivateDnsName();
    this.architecture = instance.getArchitecture();
    this.state = instance.getState().getName();
    this.ramdisk = instance.getRamdiskId();
    this.subnet = instance.getSubnetId();
    this.rootDeviceName = instance.getRootDeviceName();
    this.rootDeviceType = instance.getRootDeviceType();
    this.stateTransitionReason = instance.getStateTransitionReason();
    this.spotInstanceRequest = instance.getSpotInstanceRequestId();
    this.virtualizationType = instance.getVirtualizationType();
    this.sourceDestCheck = instance.getSourceDestCheck();
    this.launchTime = new DateTime(instance.getLaunchTime());

    if (instance.getIamInstanceProfile() != null) {
        this.iamInstanceProfile = instance.getIamInstanceProfile().getArn().toString();
    } else {
        this.iamInstanceProfile = null;
    }

    final StateReason stateReason = instance.getStateReason();
    if (stateReason != null)
        this.stateReason = stateReason.getMessage();
    else
        this.stateReason = null;

    this.securityGroups = new ArrayList<>();
    for (GroupIdentifier identifier : instance.getSecurityGroups()) {
        this.securityGroups.add(new SecurityGroup(identifier));
    }

    this.tags = new HashMap<>();
    for (Tag tag : instance.getTags()) {
        this.tags.put(tag.getKey(), tag.getValue());
    }
}
 
Example #19
Source File: EC2Instance.java    From billow with Apache License 2.0 4 votes vote down vote up
public SecurityGroup(GroupIdentifier id) {
    this.id = id.getGroupId();
    this.name = id.getGroupName();
}
 
Example #20
Source File: CommonTestUtils.java    From pacbot with Apache License 2.0 4 votes vote down vote up
public static GroupIdentifier getGroupIdentifier(String groupId){
    GroupIdentifier groupIdentifier = new GroupIdentifier();
    groupIdentifier.setGroupId(groupId);
    return groupIdentifier;
}
 
Example #21
Source File: CommonTestUtils.java    From pacbot with Apache License 2.0 4 votes vote down vote up
public static Set<GroupIdentifier> getEmptySetGroupIdentifier(String passRuleResourceId) {
    Set<GroupIdentifier> commonSet = new HashSet<>();
    return commonSet;
}
 
Example #22
Source File: CommonTestUtils.java    From pacbot with Apache License 2.0 4 votes vote down vote up
public static List<GroupIdentifier> getListSecurityGroupId() {
    List<GroupIdentifier> groupIdentifiers = new ArrayList<>();
    groupIdentifiers.add(getGroupIdentifier("123"));
    return groupIdentifiers;
}
 
Example #23
Source File: PacmanUtils.java    From pacbot with Apache License 2.0 4 votes vote down vote up
public static Map<String, Boolean> isAccessbleToAll(Set<GroupIdentifier> secuityGroupSet, int target,
        String sgRulesUrl, String cidrIp) throws Exception {
    String fromPort = null;
    String toPort = null;
    String ipprotocol = null;
    JsonObject resultJson = null;
    LinkedHashMap<String, Boolean> openPorts = new LinkedHashMap<>();

    for (GroupIdentifier securityGrp : secuityGroupSet) {
        JsonParser jsonParser = new JsonParser();
        Map<String, Object> mustFilter = new HashMap<>();
        Map<String, Object> mustNotFilter = new HashMap<>();
        HashMultimap<String, Object> shouldFilter = HashMultimap.create();
        Map<String, Object> mustTermsFilter = new HashMap<>();
        mustFilter.put(convertAttributetoKeyword(PacmanRuleConstants.GROUP_ID), securityGrp.getGroupId());
        mustFilter.put(convertAttributetoKeyword(PacmanRuleConstants.CIDRIP), cidrIp);
        mustFilter.put(convertAttributetoKeyword(PacmanSdkConstants.TYPE), PacmanRuleConstants.INBOUND);
        resultJson = RulesElasticSearchRepositoryUtil.getQueryDetailsFromES(sgRulesUrl, mustFilter, mustNotFilter,
                shouldFilter, null, 0, mustTermsFilter, null,null);
        if (resultJson != null) {
            JsonObject hitsJson = (JsonObject) jsonParser
                    .parse(resultJson.get(PacmanRuleConstants.HITS).toString());
            JsonArray hitsArray = hitsJson.getAsJsonArray(PacmanRuleConstants.HITS);
            logger.info(sgRulesUrl);
            for (int i = 0; i < hitsArray.size(); i++) {
                JsonObject source = hitsArray.get(i).getAsJsonObject().get(PacmanRuleConstants.SOURCE)
                        .getAsJsonObject();
                fromPort = source.get("fromport").getAsString();
                toPort = source.get("toport").getAsString();
                ipprotocol = source.get("ipprotocol").getAsString();
                logger.info(fromPort);
                logger.info(toPort);
                logger.info(ipprotocol);
                if (!org.apache.commons.lang.StringUtils.isEmpty(fromPort)
                        && !org.apache.commons.lang.StringUtils.isEmpty(toPort)) {

                    if (!"All".equalsIgnoreCase(fromPort)) {

                        if (Long.parseLong(fromPort) <= target) {
                            getFromAndToPorts(fromPort, toPort, ipprotocol, openPorts);
                        }
                    } else {
                        getFromAndToPorts(fromPort, toPort, ipprotocol, openPorts);
                    }
                }
            }
        }
    }
    return openPorts;
}
 
Example #24
Source File: CommonTestUtils.java    From pacbot with Apache License 2.0 4 votes vote down vote up
public static GroupIdentifier getGroupIdentifier(String groupId){
    GroupIdentifier groupIdentifier = new GroupIdentifier();
    groupIdentifier.setGroupId(groupId);
    return groupIdentifier;
}
 
Example #25
Source File: CommonTestUtils.java    From pacbot with Apache License 2.0 4 votes vote down vote up
public static Set<GroupIdentifier> getEmptySetGroupIdentifier(String passRuleResourceId) {
    Set<GroupIdentifier> commonSet = new HashSet<>();
    return commonSet;
}
 
Example #26
Source File: CommonTestUtils.java    From pacbot with Apache License 2.0 4 votes vote down vote up
public static Set<GroupIdentifier> getSetGroupIdentifier(String passRuleResourceId) {
    Set<GroupIdentifier> commonSet = new HashSet<>();
    commonSet.add(getGroupIdentifier(passRuleResourceId));
    return commonSet;
}
 
Example #27
Source File: CommonTestUtils.java    From pacbot with Apache License 2.0 4 votes vote down vote up
public static List<GroupIdentifier> getListSecurityGroupId() {
    List<GroupIdentifier> groupIdentifiers = new ArrayList<>();
    groupIdentifiers.add(getGroupIdentifier("123"));
    return groupIdentifiers;
}
 
Example #28
Source File: Instance.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Gets the value of the SecurityGroups attribute. If this resource is not
 * yet loaded, a call to {@code load()} is made to retrieve the value of the
 * attribute.
 */
List<GroupIdentifier> getSecurityGroups();
 
Example #29
Source File: NetworkInterface.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Gets the value of the Groups attribute. If this resource is not yet
 * loaded, a call to {@code load()} is made to retrieve the value of the
 * attribute.
 */
List<GroupIdentifier> getGroups();