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

The following examples show how to use com.amazonaws.services.ec2.model.SecurityGroup. 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: SecurityGroupsTableProviderTest.java    From aws-athena-query-federation with Apache License 2.0 6 votes vote down vote up
@Override
protected void setUpRead()
{
    when(mockEc2.describeSecurityGroups(any(DescribeSecurityGroupsRequest.class)))
            .thenAnswer((InvocationOnMock invocation) -> {
                DescribeSecurityGroupsRequest request = (DescribeSecurityGroupsRequest) invocation.getArguments()[0];

                assertEquals(getIdValue(), request.getGroupIds().get(0));
                DescribeSecurityGroupsResult mockResult = mock(DescribeSecurityGroupsResult.class);
                List<SecurityGroup> values = new ArrayList<>();
                values.add(makeSecurityGroup(getIdValue()));
                values.add(makeSecurityGroup(getIdValue()));
                values.add(makeSecurityGroup("fake-id"));
                when(mockResult.getSecurityGroups()).thenReturn(values);
                return mockResult;
            });
}
 
Example #2
Source File: AwsDescribeServiceImpl.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<SecurityGroup> getSecurityGroups(Long userNo, Long platformNo) {
    // セキュリティグループを取得
    AwsProcessClient awsProcessClient = awsProcessClientFactory.createAwsProcessClient(userNo, platformNo);
    DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest();
    PlatformAws platformAws = platformAwsDao.read(platformNo);
    if (BooleanUtils.isTrue(platformAws.getVpc())) {
        // VPCの場合、VPC IDが同じものを抽出
        request.withFilters(new Filter().withName("vpc-id").withValues(platformAws.getVpcId()));
    } else {
        // 非VPCの場合、VPC IDが空のものを抽出
        request.withFilters(new Filter().withName("vpc-id").withValues(""));
    }
    DescribeSecurityGroupsResult result = awsProcessClient.getEc2Client().describeSecurityGroups(request);
    List<SecurityGroup> securityGroups = result.getSecurityGroups();

    // ソート
    Collections.sort(securityGroups, Comparators.COMPARATOR_SECURITY_GROUP);

    return securityGroups;
}
 
Example #3
Source File: SecurityGroupsCheckerImplTest.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
    final ClientProvider mockClientProvider = mock(ClientProvider.class);
    final AmazonEC2Client mockEC2 = mock(AmazonEC2Client.class);
    mockPredicate = (Predicate<IpPermission>) mock(Predicate.class);

    when(mockClientProvider.getClient(any(), any(), any())).thenReturn(mockEC2);

    securityGroupsChecker = new SecurityGroupsCheckerImpl(mockClientProvider, mockPredicate);

    final DescribeSecurityGroupsResult securityGroups = new DescribeSecurityGroupsResult()
            .withSecurityGroups(new SecurityGroup()
                    .withGroupId("sg-12345678")
                    .withGroupName("my-sec-group")
                    .withIpPermissions(new IpPermission()
                            .withIpProtocol("tcp")
                            .withIpv4Ranges(new IpRange().withCidrIp("0.0.0.0/0"))
                            .withFromPort(0)
                            .withToPort(65535)
                            .withIpv6Ranges(new Ipv6Range().withCidrIpv6("::/0"))
                            .withUserIdGroupPairs(new UserIdGroupPair()
                                    .withUserId("111222333444")
                                    .withGroupId("sg-11223344"))));
    when(mockEC2.describeSecurityGroups(any())).thenReturn(securityGroups);
}
 
Example #4
Source File: SecurityGroupsCheckerImpl.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, SecurityGroupCheckDetails> check(final Collection<String> groupIds, final String account, final Region region) {
    final DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest();
    describeSecurityGroupsRequest.setGroupIds(groupIds);
    final AmazonEC2Client amazonEC2Client = clientProvider.getClient(
            AmazonEC2Client.class,
            account, region);
    final DescribeSecurityGroupsResult describeSecurityGroupsResult = amazonEC2Client.describeSecurityGroups(
            describeSecurityGroupsRequest);


    final ImmutableMap.Builder<String, SecurityGroupCheckDetails> result = ImmutableMap.builder();

    for (final SecurityGroup securityGroup : describeSecurityGroupsResult.getSecurityGroups()) {
        final List<String> offendingRules = securityGroup.getIpPermissions().stream()
                .filter(isOffending)
                .map(Object::toString)
                .collect(toList());
        if (!offendingRules.isEmpty()) {
            final SecurityGroupCheckDetails details = new SecurityGroupCheckDetails(
                    securityGroup.getGroupName(), ImmutableList.copyOf(offendingRules));
            result.put(securityGroup.getGroupId(), details);
        }
    }
    return result.build();
}
 
Example #5
Source File: SGLookupService.java    From Gatekeeper with Apache License 2.0 6 votes vote down vote up
private List<String> loadSgsForAccountRegion(AWSEnvironment environment) {
    logger.info("Grabbing SGs for environment " + environment);
    DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest();

    Filter groupNameFilter = new Filter();
    groupNameFilter.setName("group-name");
    groupNameFilter.setValues(Arrays.asList(securityGroupNames.split(",")));

    AmazonEC2Client amazonEC2Client = awsSessionService.getEC2Session(environment);
    DescribeSecurityGroupsResult result = amazonEC2Client.describeSecurityGroups(describeSecurityGroupsRequest.withFilters(groupNameFilter));

    logger.info("found " + result.getSecurityGroups().size() + " Security Groups with name(s) '" + securityGroupNames + "'");
    return result.getSecurityGroups().stream()
            .map(SecurityGroup::getGroupId)
            .collect(Collectors.toList());

}
 
Example #6
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch security groups test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchSecurityGroupsTest() throws Exception {
    
    mockStatic(AmazonEC2ClientBuilder.class);
    AmazonEC2 ec2Client = PowerMockito.mock(AmazonEC2.class);
    AmazonEC2ClientBuilder amazonEC2ClientBuilder = PowerMockito.mock(AmazonEC2ClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonEC2ClientBuilder.standard()).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withCredentials(anyObject())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.withRegion(anyString())).thenReturn(amazonEC2ClientBuilder);
    when(amazonEC2ClientBuilder.build()).thenReturn(ec2Client);
    
    DescribeSecurityGroupsResult describeSecurityGroupsResult = new DescribeSecurityGroupsResult();
    List<SecurityGroup> secGrpList = new ArrayList<>();
    secGrpList.add(new SecurityGroup());
    describeSecurityGroupsResult.setSecurityGroups(secGrpList);
    when(ec2Client.describeSecurityGroups()).thenReturn(describeSecurityGroupsResult);
    assertThat(inventoryUtil.fetchSecurityGroups(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
    
}
 
Example #7
Source File: InventoryUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch security groups.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @param accountName the account name
 * @return the map
 */
public static Map<String,List<SecurityGroup>> fetchSecurityGroups(BasicSessionCredentials temporaryCredentials, String skipRegions,String accountId,String accountName){
	log.info("skipRegionseee" + skipRegions);
	Map<String,List<SecurityGroup>> secGrpList = new LinkedHashMap<>();
	AmazonEC2 ec2Client ;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE+accountId + "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"Security Group\" , \"region\":\"" ;
	log.info("sgregion" + RegionUtils.getRegions().toString());
	for(Region region : RegionUtils.getRegions()) {
		try{
			if(!skipRegions.contains(region.getName())){
				ec2Client = AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials)).withRegion(region.getName()).build();
				DescribeSecurityGroupsResult rslt =  ec2Client.describeSecurityGroups();
				List<SecurityGroup> secGrpListTemp = rslt.getSecurityGroups();
				if( !secGrpListTemp.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId +" Type : Security Group "+region.getName()+" >> " + secGrpListTemp.size());
					secGrpList.put(accountId+delimiter+accountName+delimiter+region.getName(),secGrpListTemp);
				}

			}
		}catch(Exception e){
			log.warn(expPrefix+ region.getName()+InventoryConstants.ERROR_CAUSE +e.getMessage()+"\"}");
			ErrorManageUtil.uploadError(accountId,region.getName(),"sg",e.getMessage());
		}
	}
	return secGrpList;
}
 
Example #8
Source File: AmazonIpRuleManager.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<String> listRuleSets() {
    DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest();
    DescribeSecurityGroupsResult result = null;
    try {
        result = client.describeSecurityGroups( request );
    }
    catch ( Exception e ) {
        LOG.warn( "Error while getting security groups", e );
        return new LinkedList<String>();
    }
    Collection<String> groups = new ArrayList<String>();
    for( SecurityGroup group : result.getSecurityGroups() ) {
        groups.add( group.getGroupName() );
    }
    return groups;
}
 
Example #9
Source File: CommonTestUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
public static SecurityGroup getSecurityGroup(String groupId){
	UserIdGroupPair groupPair = new UserIdGroupPair();
	groupPair.setGroupId("123");
	List<UserIdGroupPair> userIdGroupPairs = new ArrayList<UserIdGroupPair>();
	userIdGroupPairs.add(groupPair);
	
	
	IpPermission ipPermission = new IpPermission();
	ipPermission.setFromPort(80);
	ipPermission.setUserIdGroupPairs(userIdGroupPairs);
	List<IpPermission> ipPermissions = new ArrayList<IpPermission>();
	ipPermissions.add(ipPermission);
	SecurityGroup securityGroup = new SecurityGroup();
	securityGroup.setGroupId(groupId);
	securityGroup.setIpPermissions(ipPermissions);
    return securityGroup;
}
 
Example #10
Source File: SecurityGroupsTableProviderTest.java    From aws-athena-query-federation with Apache License 2.0 6 votes vote down vote up
private SecurityGroup makeSecurityGroup(String id)
{
    return new SecurityGroup()
            .withGroupId(id)
            .withGroupName("name")
            .withDescription("description")
            .withIpPermissions(new IpPermission()
                    .withIpProtocol("protocol")
                    .withFromPort(100)
                    .withToPort(100)
                    .withIpv4Ranges(new IpRange().withCidrIp("cidr").withDescription("description"))

                    .withIpv6Ranges(new Ipv6Range().withCidrIpv6("cidr").withDescription("description"))
                    .withPrefixListIds(new PrefixListId().withPrefixListId("prefix").withDescription("description"))
                    .withUserIdGroupPairs(new UserIdGroupPair().withGroupId("group_id").withUserId("user_id"))
            );
}
 
Example #11
Source File: Ec2NetworkTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Test describing security group.
 */
@Test(timeout = TIMEOUT_LEVEL1)
public final void describeSecurityGroupTest() {
    log.info("Start describing security group test");
    createSecurityGroupTest();
    SecurityGroup securityGroup = getSecurityGroup();

    Assert.assertNotNull("security group should not be null", securityGroup);
    Assert.assertNotNull("group id should not be null", securityGroup.getGroupId());
    Assert.assertNotNull("vpc id should not be null", securityGroup.getVpcId());
}
 
Example #12
Source File: AwsPlatformResources.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private List<SecurityGroup> fetchSecurityGroups(AmazonEC2Client ec2Client, DescribeSecurityGroupsRequest describeSecurityGroupsRequest) {
    try {
        return ec2Client.describeSecurityGroups(describeSecurityGroupsRequest).getSecurityGroups();
    } catch (AmazonEC2Exception e) {
        if (e.getStatusCode() == HttpStatus.BAD_REQUEST.value() || e.getStatusCode() == HttpStatus.NOT_FOUND.value()) {
            throw new PermanentlyFailedException(e.getErrorMessage(), e);
        } else {
            throw e;
        }
    }
}
 
Example #13
Source File: AwsPlatformResources.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public CloudSecurityGroups securityGroups(CloudCredential cloudCredential, Region region, Map<String, String> filters) {
    Map<String, Set<CloudSecurityGroup>> result = new HashMap<>();
    Set<CloudSecurityGroup> cloudSecurityGroups = new HashSet<>();
    AmazonEC2Client ec2Client = awsClient.createAccess(new AwsCredentialView(cloudCredential), region.value());

    //create securitygroup filter view
    PlatformResourceSecurityGroupFilterView filter = new PlatformResourceSecurityGroupFilterView(filters);

    DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest();
    // If the filtervalue is provided then we should filter only for those securitygroups
    if (!Strings.isNullOrEmpty(filter.getVpcId())) {
        describeSecurityGroupsRequest.withFilters(new Filter("vpc-id", singletonList(filter.getVpcId())));
    }
    if (!Strings.isNullOrEmpty(filter.getGroupId())) {
        describeSecurityGroupsRequest.withGroupIds(filter.getGroupId());
    }
    if (!Strings.isNullOrEmpty(filter.getGroupName())) {
        describeSecurityGroupsRequest.withGroupNames(filter.getGroupName());
    }

    for (SecurityGroup securityGroup : fetchSecurityGroups(ec2Client, describeSecurityGroupsRequest)) {
        Map<String, Object> properties = new HashMap<>();
        properties.put("vpcId", securityGroup.getVpcId());
        properties.put("description", securityGroup.getDescription());
        properties.put("ipPermissions", securityGroup.getIpPermissions());
        properties.put("ipPermissionsEgress", securityGroup.getIpPermissionsEgress());
        cloudSecurityGroups.add(new CloudSecurityGroup(securityGroup.getGroupName(), securityGroup.getGroupId(), properties));
    }
    result.put(region.value(), cloudSecurityGroups);
    return new CloudSecurityGroups(result);
}
 
Example #14
Source File: EditLoadBalancer.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
/**
 * SecurityGroupNameの一覧を取得する
 *
 * @param userNo ユーザ番号
 * @param platformNo プラットフォーム番号
 * @param vpcId vpcId(vpc以外の場合はNULL)
 * @return SecurityGroupNameの一覧
 */
private List<String> getSecurityGroupNames(Long userNo, Long platformNo, String vpcId) {
    List<String> groupNames = new ArrayList<String>();
    List<SecurityGroup> groups = awsDescribeService.getSecurityGroups(userNo, platformNo);
    for (SecurityGroup group : groups) {
        groupNames.add(group.getGroupName());
    }
    return groupNames;
}
 
Example #15
Source File: SecurityGroupsTableProvider.java    From aws-athena-query-federation with Apache License 2.0 5 votes vote down vote up
/**
 * Maps an each SecurityGroup rule (aka IpPermission) to a row in the response.
 *
 * @param securityGroup The SecurityGroup that owns the permission entry.
 * @param permission The permission entry (aka rule) to map.
 * @param direction The direction (EGRESS or INGRESS) of the rule.
 * @param spiller The BlockSpiller to use when we want to write a matching row to the response.
 * @note The current implementation is rather naive in how it maps fields. It leverages a static
 * list of fields that we'd like to provide and then explicitly filters and converts each field.
 */
private void instanceToRow(SecurityGroup securityGroup,
        IpPermission permission,
        String direction,
        BlockSpiller spiller)
{
    spiller.writeRows((Block block, int row) -> {
        boolean matched = true;

        matched &= block.offerValue("id", row, securityGroup.getGroupId());
        matched &= block.offerValue("name", row, securityGroup.getGroupName());
        matched &= block.offerValue("description", row, securityGroup.getDescription());
        matched &= block.offerValue("from_port", row, permission.getFromPort());
        matched &= block.offerValue("to_port", row, permission.getFromPort());
        matched &= block.offerValue("protocol", row, permission.getIpProtocol());
        matched &= block.offerValue("direction", row, permission.getIpProtocol());

        List<String> ipv4Ranges = permission.getIpv4Ranges().stream()
                .map(next -> next.getCidrIp() + ":" + next.getDescription()).collect(Collectors.toList());
        matched &= block.offerComplexValue("ipv4_ranges", row, FieldResolver.DEFAULT, ipv4Ranges);

        List<String> ipv6Ranges = permission.getIpv6Ranges().stream()
                .map(next -> next.getCidrIpv6() + ":" + next.getDescription()).collect(Collectors.toList());
        matched &= block.offerComplexValue("ipv6_ranges", row, FieldResolver.DEFAULT, ipv6Ranges);

        List<String> prefixLists = permission.getPrefixListIds().stream()
                .map(next -> next.getPrefixListId() + ":" + next.getDescription()).collect(Collectors.toList());
        matched &= block.offerComplexValue("prefix_lists", row, FieldResolver.DEFAULT, prefixLists);

        List<String> userIdGroups = permission.getUserIdGroupPairs().stream()
                .map(next -> next.getUserId() + ":" + next.getGroupId())
                .collect(Collectors.toList());
        matched &= block.offerComplexValue("user_id_groups", row, FieldResolver.DEFAULT, userIdGroups);

        return matched ? 1 : 0;
    });
}
 
Example #16
Source File: AwsCommonProcess.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
public List<SecurityGroup> describeSecurityGroupsByVpcId(AwsProcessClient awsProcessClient, String vpcId) {
    DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest();
    request.withFilters(new Filter().withName("vpc-id").withValues(vpcId));
    DescribeSecurityGroupsResult result = awsProcessClient.getEc2Client().describeSecurityGroups(request);
    List<SecurityGroup> securityGroups = result.getSecurityGroups();

    return securityGroups;
}
 
Example #17
Source File: BaseTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Describe security group.
 *
 * @return SecurityGroup
 */
protected final SecurityGroup getSecurityGroup() {
    SecurityGroup cellGroup = null;

    DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest();
    DescribeSecurityGroupsResult result = amazonEC2Client.describeSecurityGroups(req);
    if (result != null && !result.getSecurityGroups().isEmpty()) {
        cellGroup = result.getSecurityGroups().get(0);
    }

    return cellGroup;
}
 
Example #18
Source File: SecurityGroupConverter.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected SecurityGroup convertObject(GroupDescription from) {
    SecurityGroup to = new SecurityGroup();

    to.setOwnerId(from.getOwner());
    to.setGroupName(from.getName());
    to.setDescription(from.getDescription());
    to.setIpPermissions(new IpPermissionConverter().convert(from.getPermissions()));

    return to;
}
 
Example #19
Source File: MockAwsDescribeService.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
@Override
public List<SecurityGroup> getSecurityGroups(Long userNo, Long platformNo) {
    List<SecurityGroup> groups = new ArrayList<SecurityGroup>();

    groups.add(new SecurityGroup().withGroupName("default"));
    groups.add(new SecurityGroup().withGroupName("group01"));
    groups.add(new SecurityGroup().withGroupName("group02"));

    return groups;
}
 
Example #20
Source File: EC2Mockup.java    From development with Apache License 2.0 5 votes vote down vote up
public void createDescribeSecurityGroupResult(String vpcId,
        String SecurityGroupIds) {
    Collection<SecurityGroup> securityGroup = new ArrayList<SecurityGroup>();
    for (int i = 0; i < SecurityGroupIds.split(",").length; i++) {
        securityGroup.add(new SecurityGroup()
                .withGroupId(SecurityGroupIds.split(",")[i])
                .withGroupName(SecurityGroupIds.split(",")[i])
                .withVpcId(vpcId));
    }
    DescribeSecurityGroupsResult securityGroupResult = new DescribeSecurityGroupsResult()
            .withSecurityGroups(securityGroup);
    doReturn(securityGroupResult).when(ec2).describeSecurityGroups();
}
 
Example #21
Source File: DescribeSecurityGroups.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
{
    final String USAGE =
        "To run this example, supply a group id\n" +
        "Ex: DescribeSecurityGroups <group-id>\n";

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

    String group_id = args[0];

    final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();

    DescribeSecurityGroupsRequest request =
        new DescribeSecurityGroupsRequest()
            .withGroupIds(group_id);

    DescribeSecurityGroupsResult response =
        ec2.describeSecurityGroups(request);

    for(SecurityGroup group : response.getSecurityGroups()) {
        System.out.printf(
            "Found security group with id %s, " +
            "vpc id %s " +
            "and description %s",
            group.getGroupId(),
            group.getVpcId(),
            group.getDescription());
    }
}
 
Example #22
Source File: FileManager.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Generate sec group file.
 *
 * @param secGrpMap the sec grp map
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void generateSecGroupFile(Map<String, List<SecurityGroup>> secGrpMap) throws IOException {
	String fieldNames;
	String keys;
	fieldNames = "GroupId`Description`GroupName`OwnerId`vpcid";
	keys = "discoverydate`accountid`accountname`region`groupid`description`groupname`ownerid`vpcid";
	FileGenerator.generateJson(secGrpMap, fieldNames, "aws-sg.data",keys);
	fieldNames = "GroupId`tags.key`tags.value";
	keys = "discoverydate`accountid`accountname`region`groupid`key`value";
	FileGenerator.generateJson(secGrpMap, fieldNames, "aws-sg-tags.data",keys);

	Map<String, List<SGRuleVH>> secGrp = new HashMap<>();
	secGrpMap.forEach((k,v)-> {
			List<SGRuleVH> sgruleList = new ArrayList<>();
			v.forEach(sg -> {
				String groupId = sg.getGroupId();
				sgruleList.addAll(getRuleInfo(groupId,"inbound",sg.getIpPermissions()));
				sgruleList.addAll(getRuleInfo(groupId,"outbound",sg.getIpPermissionsEgress()));
			});
			secGrp.put(k,sgruleList);
		}
	);
	fieldNames = "groupId`type`ipProtocol`fromPort`toPort`cidrIp`cidrIpv6";
	keys = "discoverydate`accountid`accountname`region`groupid`type`ipprotocol`fromport`toport`cidrip`cidripv6";
	FileGenerator.generateJson(secGrp, fieldNames, "aws-sg-rules.data",keys);

}
 
Example #23
Source File: PublicAccessAutoFix.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the existing security group details.
 *
 * @param securityGroupList the security group list
 * @param ec2Client the ec 2 client
 * @return the existing security group details
 */
public static List<SecurityGroup> getExistingSecurityGroupDetails(Set<String> securityGroupList, AmazonEC2 ec2Client) {
	RetryConfig config = RetryConfig.custom().maxAttempts(MAX_ATTEMPTS).waitDuration(Duration.ofSeconds(WAIT_INTERVAL)).build();
	RetryRegistry registry = RetryRegistry.of(config);
	DescribeSecurityGroupsRequest securityGroups = new DescribeSecurityGroupsRequest();
  		securityGroups.setGroupIds(securityGroupList);
	Retry retry = registry.retry(securityGroups.toString());
  		
	Function<Integer, List<SecurityGroup>> decorated
	  =  Retry.decorateFunction(retry, (Integer s) -> {
		  DescribeSecurityGroupsResult  groupsResult =  ec2Client.describeSecurityGroups(securityGroups);
		  return groupsResult.getSecurityGroups();
	    });
	return decorated.apply(1);
}
 
Example #24
Source File: WinServerEdit.java    From primecloud-controller with GNU General Public License v2.0 4 votes vote down vote up
private void loadData() {
    AwsDescribeService awsDescribeService = BeanContext.getBean(AwsDescribeService.class);
    Long platformNo = platform.getPlatform().getPlatformNo();

    // キーペア情報を取得
    List<KeyPairInfo> keyPairInfos = awsDescribeService.getKeyPairs(ViewContext.getUserNo(), platformNo);
    List<String> keyNames = new ArrayList<String>();
    for (KeyPairInfo keyPairInfo : keyPairInfos) {
        keyNames.add(keyPairInfo.getKeyName());
    }
    this.keyNames = keyNames;

    // セキュリティグループ情報を取得
    List<String> groupNames = new ArrayList<String>();
    List<SecurityGroup> securityGroups = awsDescribeService.getSecurityGroups(ViewContext.getUserNo(),
            platformNo);
    for (SecurityGroup securityGroup : securityGroups) {
        groupNames.add(securityGroup.getGroupName());
    }
    this.groupNames = groupNames;

    // VPCの場合
    if (BooleanUtils.isTrue(platform.getPlatformAws().getVpc())) {
        // サブネット情報の取得
        List<Subnet> subnets = awsDescribeService.getSubnets(ViewContext.getUserNo(), platformNo);
        this.subnets = subnets;
    }
    // 非VPCの場合
    else {
        // ゾーン情報の取得
        List<AvailabilityZone> zones = awsDescribeService.getAvailabilityZones(ViewContext.getUserNo(),
                platformNo);
        if (BooleanUtils.isNotTrue(platform.getPlatformAws().getEuca())) {
            // EC2の場合、空行を先頭に追加してゾーンを無指定にできるようにする
            zones.add(0, new AvailabilityZone());
        }
        this.zones = zones;
    }

    // ElasticIp情報の取得
    List<AwsAddress> elasticIps = awsDescribeService.getAddresses(ViewContext.getUserNo(), platformNo);
    this.elasticIps = elasticIps;
}
 
Example #25
Source File: WinLoadBalancerEdit.java    From primecloud-controller with GNU General Public License v2.0 4 votes vote down vote up
private void loadData() {
    Long userNo = ViewContext.getUserNo();
    Long farmNo = ViewContext.getFarmNo();

    // ロードバランサ情報を取得
    LoadBalancerService loadBalancerService = BeanContext.getBean(LoadBalancerService.class);
    List<LoadBalancerDto> loadBalancers = loadBalancerService.getLoadBalancers(farmNo);
    for (LoadBalancerDto loadBalancer : loadBalancers) {
        if (loadBalancerNo.equals(loadBalancer.getLoadBalancer().getLoadBalancerNo())) {
            this.loadBalancer = loadBalancer;
            break;
        }
    }

    // ロードバランサのプラットフォーム情報を取得
    Long platformNo = loadBalancer.getLoadBalancer().getPlatformNo();
    List<LoadBalancerPlatformDto> platforms = loadBalancerService.getPlatforms(userNo);
    for (LoadBalancerPlatformDto platform : platforms) {
        if (platformNo.equals(platform.getPlatform().getPlatformNo())) {
            this.platform = platform;
            break;
        }
    }

    // コンポーネント情報を取得
    ComponentService componentService = BeanContext.getBean(ComponentService.class);
    components = componentService.getComponents(farmNo);

    // UltraMonkeyロードバランサの場合
    if (PCCConstant.LOAD_BALANCER_ULTRAMONKEY.equals(loadBalancer.getLoadBalancer().getType())) {
        // インスタンスを特定する
        this.loadBalancerInstanceNo = loadBalancerService.getLoadBalancerInstance(loadBalancerNo);
    }
    // AWSロードバランサの場合
    if (PCCConstant.LOAD_BALANCER_ELB.equals(loadBalancer.getLoadBalancer().getType())) {
        // VPCの場合
        if (BooleanUtils.isTrue(platform.getPlatformAws().getVpc())) {
            AwsDescribeService awsDescribeService = BeanContext.getBean(AwsDescribeService.class);

            // サブネットを取得
            this.subnets = new ArrayList<Subnet>();
            List<Subnet> subnets = awsDescribeService.getSubnets(userNo, platformNo);
            for (Subnet subnet : subnets) {
                this.subnets.add(subnet);
            }

            // セキュリティグループを取得
            this.securityGroups = new ArrayList<String>();
            List<SecurityGroup> groups = awsDescribeService.getSecurityGroups(userNo, platformNo);
            for (SecurityGroup group : groups) {
                this.securityGroups.add(group.getGroupName());
            }
        }
    }
}
 
Example #26
Source File: Comparators.java    From primecloud-controller with GNU General Public License v2.0 4 votes vote down vote up
@Override
public int compare(SecurityGroup o1, SecurityGroup o2) {
    return o1.getGroupName().compareTo(o2.getGroupName());
}
 
Example #27
Source File: AwsLoadBalancerProcess.java    From primecloud-controller with GNU General Public License v2.0 4 votes vote down vote up
public void applySecurityGroups(AwsProcessClient awsProcessClient, Long loadBalancerNo) {
    // 非VPCの場合はスキップ
    if (BooleanUtils.isNotTrue(awsProcessClient.getPlatformAws().getVpc())) {
        return;
    }

    AwsLoadBalancer awsLoadBalancer = awsLoadBalancerDao.read(loadBalancerNo);

    // 現在設定されているSecurityGroup
    LoadBalancerDescription description = awsCommonProcess.describeLoadBalancer(awsProcessClient,
            awsLoadBalancer.getName());
    List<String> groupIds = description.getSecurityGroups();

    // 新しく設定するSecurityGroup
    List<String> newGroupIds = new ArrayList<String>();
    List<SecurityGroup> securityGroups = awsCommonProcess.describeSecurityGroupsByVpcId(awsProcessClient,
            awsProcessClient.getPlatformAws().getVpcId());
    for (String groupName : StringUtils.split(awsLoadBalancer.getSecurityGroups(), ",")) {
        groupName = groupName.trim();
        for (SecurityGroup securityGroup : securityGroups) {
            if (StringUtils.equals(groupName, securityGroup.getGroupName())) {
                newGroupIds.add(securityGroup.getGroupId());
                break;
            }
        }
    }

    // SecurityGroupに変更がない場合はスキップ
    if (groupIds.size() == newGroupIds.size() && groupIds.containsAll(newGroupIds)) {
        return;
    }

    // セキュリティグループを変更
    ApplySecurityGroupsToLoadBalancerRequest request = new ApplySecurityGroupsToLoadBalancerRequest();
    request.withLoadBalancerName(awsLoadBalancer.getName());
    request.withSecurityGroups(newGroupIds);
    awsProcessClient.getElbClient().applySecurityGroupsToLoadBalancer(request);

    if (log.isInfoEnabled()) {
        log.info(MessageUtils.getMessage("IPROCESS-200225", awsLoadBalancer.getName()));
    }

    // イベントログ出力
    processLogger.debug(null, null, "AwsElbSecurityGroupsConfig",
            new Object[] { awsProcessClient.getPlatform().getPlatformName(), awsLoadBalancer.getName() });
}
 
Example #28
Source File: SetVPCSecurityGroupID.java    From Raigad with Apache License 2.0 4 votes vote down vote up
public void execute() {
    AmazonEC2 client = null;

    try {
        client = getEc2Client();

        //Get All the Existing Sec Group Ids
        String[] securityGroupIds = SystemUtils.getSecurityGroupIds(config.getMacIdForInstance());
        DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest().withGroupIds(securityGroupIds);
        DescribeSecurityGroupsResult result = client.describeSecurityGroups(req);

        boolean securityGroupFound = false;

        for (SecurityGroup securityGroup : result.getSecurityGroups()) {
            logger.info("Read " + securityGroup.getGroupName());

            if (securityGroup.getGroupName().equals(config.getACLGroupNameForVPC())) {
                logger.info("Found matching security group name: " + securityGroup.getGroupName());

                // Setting configuration value with the correct SG ID
                config.setACLGroupIdForVPC(securityGroup.getGroupId());
                securityGroupFound = true;

                break;
            }
        }

        // If correct SG was not found, throw Exception
        if (!securityGroupFound) {
            throw new RuntimeException("Cannot find matching security group for " + config.getACLGroupNameForVPC());
        }
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
    finally {
        if (client != null) {
            client.shutdown();
        }
    }
}
 
Example #29
Source File: GroupController.java    From sequenceiq-samples with Apache License 2.0 4 votes vote down vote up
@RequestMapping(method = RequestMethod.GET, value = {"/groups/list"})
@ResponseBody
public List<SecurityGroup> describeSecurityGroupList(@RequestParam("accessKey") String accessKey, @RequestParam("secretKey") String secretKey) {
	return awsec2Service.listSecurityGroups(awsCredentialsFactory.createSimpleAWSCredentials(accessKey, secretKey));
}
 
Example #30
Source File: EC2Communication.java    From development with Apache License 2.0 4 votes vote down vote up
/**
 * Checks whether exiting SecurityGroups is present.
 * 
 * @param securityGroupNames
 * @param vpcId
 *            The ID of the VPC the subnet is in.A virtual private cloud
 *            (VPC) is a virtual network dedicated to your AWS account. It
 *            is logically isolated from other virtual networks in the AWS
 *            cloud. You can launch your AWS resources, such as Amazon EC2
 *            instances, into your VPC.
 * @return <code>Collection<String> </code> if the matches one of the
 *         securityGroupNames and vpcId
 * 
 */
public Collection<String> resolveSecurityGroups(
        Collection<String> securityGroupNames, String vpcId)
        throws APPlatformException {
    Collection<String> input = new HashSet<String>();
    Collection<String> result = new HashSet<String>();
    if (vpcId != null && vpcId.trim().length() == 0) {
        vpcId = null;
    }
    if (securityGroupNames != null && !securityGroupNames.isEmpty()) {
        input.addAll(securityGroupNames);
        DescribeSecurityGroupsResult securityGroups = getEC2()
                .describeSecurityGroups();
        LOGGER.debug("Search for securityGroups"
                + securityGroupNames.toString());
        for (SecurityGroup group : securityGroups.getSecurityGroups()) {
            boolean vpcMatch = false;
            if (vpcId == null) {
                vpcMatch = isNullOrEmpty(group.getVpcId());
            } else {
                vpcMatch = vpcId.equals(group.getVpcId());
            }
            if (vpcMatch && input.contains(group.getGroupName())) {
                result.add(group.getGroupId());
                input.remove(group.getGroupName());
            }
        }
        if (!input.isEmpty()) {
            StringBuffer sb = new StringBuffer();
            for (String name : input) {
                if (sb.length() > 0) {
                    sb.append(",");
                }
                sb.append(name);
            }
            throw new APPlatformException(
                    Messages.getAll("error_invalid_security_group")
                            + sb.toString());
        }
    }
    LOGGER.debug("Done with Searching for securityGroups " + result);
    return result;
}