@Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getGroupName() == null) ? 0 : getGroupName().hashCode()); hashCode = prime * hashCode + ((getIpPermissions() == null) ? 0 : getIpPermissions().hashCode()); hashCode = prime * hashCode + ((getOwnerId() == null) ? 0 : getOwnerId().hashCode()); hashCode = prime * hashCode + ((getGroupId() == null) ? 0 : getGroupId().hashCode()); hashCode = prime * hashCode + ((getIpPermissionsEgress() == null) ? 0 : getIpPermissionsEgress().hashCode()); hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode()); hashCode = prime * hashCode + ((getVpcId() == null) ? 0 : getVpcId().hashCode()); return hashCode; }
"vpc id %s " + "and description %s", group.getGroupId(), group.getVpcId(), group.getDescription());
@Override public Collection<IpRule> getRules( final String name, final boolean inbound ) { DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest().withGroupNames( name ); DescribeSecurityGroupsResult result = client.describeSecurityGroups( request ); if( result.getSecurityGroups().size() != 1 ) { return null; } Collection<IpRule> ipRules = new ArrayList<IpRule>(); List<IpPermission> permissions; if( inbound ) { permissions = result.getSecurityGroups().get( 0 ).getIpPermissions(); } else { permissions = result.getSecurityGroups().get( 0 ).getIpPermissionsEgress(); } for( IpPermission permission : permissions ) { ipRules.add( toIpRule( permission ) ); } return ipRules; }
private Set<MigrateSecurityGroupReference> getTargetReferences(SecurityGroupUpdater source) { SecurityGroup group = source.getSecurityGroup(); if (getInfrastructureApplications().contains(Names.parseName(group.getGroupName()).getApp())) { return new HashSet<>(); } return group.getIpPermissions() .stream() .map(IpPermission::getUserIdGroupPairs) .flatMap(List::stream) .filter(pair -> !pair.getGroupId().equals(group.getGroupId()) || !pair.getUserId().equals(group.getOwnerId())) .map(pair -> { NetflixAmazonCredentials account = sourceLookup.getCredentialsForId(pair.getUserId()); if (pair.getGroupName() == null) { if (account == null) { pair.setGroupName(pair.getGroupId()); } else { sourceLookup.getSecurityGroupById(account.getName(), pair.getGroupId(), pair.getVpcId()) .ifPresent(u -> pair.setGroupName(u.getSecurityGroup().getGroupName())); } } return new MigrateSecurityGroupReference(pair, account); }) .collect(Collectors.toSet()); }
public SecurityGroup unmarshall(StaxUnmarshallerContext context) throws Exception { SecurityGroup securityGroup = new SecurityGroup(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; securityGroup.setOwnerId(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; securityGroup.setGroupName(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; securityGroup.setGroupId(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; securityGroup.setDescription(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; securityGroup.getIpPermissions().add(IpPermissionStaxUnmarshaller.getInstance().unmarshall(context)); continue; securityGroup.getIpPermissionsEgress().add(IpPermissionStaxUnmarshaller.getInstance().unmarshall(context)); continue; securityGroup.setVpcId(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; securityGroup.getTags().add(TagStaxUnmarshaller.getInstance().unmarshall(context)); continue;
@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(); } }
default void addClassicLinkIngress(SecurityGroupLookup lookup, String classicLinkGroupName, String groupId, NetflixAmazonCredentials credentials, String vpcId) { if (classicLinkGroupName == null) { return; } lookup.getSecurityGroupById(credentials.getName(), groupId, vpcId).ifPresent(targetGroupUpdater -> { SecurityGroup targetGroup = targetGroupUpdater.getSecurityGroup(); lookup.getSecurityGroupByName(credentials.getName(), classicLinkGroupName, vpcId) .map(updater -> updater.getSecurityGroup().getGroupId()) .ifPresent(classicLinkGroupId -> { // don't attach if there's already some rule already configured if (targetGroup.getIpPermissions().stream() .anyMatch(p -> p.getUserIdGroupPairs().stream() .anyMatch(p2 -> p2.getGroupId().equals(classicLinkGroupId)))) { return; } targetGroupUpdater.addIngress(Collections.singletonList( new IpPermission() .withIpProtocol("tcp").withFromPort(80).withToPort(65535) .withUserIdGroupPairs( new UserIdGroupPair() .withUserId(credentials.getAccountId()) .withGroupId(classicLinkGroupId) .withVpcId(vpcId) ) )); }); }); } }
/** * 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; fieldNames = "GroupId`Description`GroupName`OwnerId`vpcid"; FileGenerator.generateFile(secGrpMap, fieldNames, "secgroup-info.data"); fieldNames = "GroupId`tags.key`tags.value"; FileGenerator.generateFile(secGrpMap, fieldNames, "secgroup-tags.data"); 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"; FileGenerator.generateFile(secGrp, fieldNames, "secgroup-rules.data"); }
String elbGroupId = null; Optional<SecurityGroup> existingGroup = appGroups.stream() .filter(g -> g.getVpcId() != null && g.getVpcId().equals(target.getVpcId()) && g.getGroupName().equals(applicationName + "-elb")) .findFirst(); if (existingGroup.isPresent()) { if (!dryRun && allowIngressFromClassic) { addClassicLinkIngress(targetLookup, getDeployDefaults().getClassicLinkSecurityGroupName(), existingGroup.get().getGroupId(), target.getCredentials(), target.getVpcId()); return existingGroup.get().getGroupId(); getTask().updateStatus(LoadBalancerMigrator.BASE_PHASE, "Creating load balancer security group " + upsertDescription.getName() + " in " + target.getCredentialAccount() + "/" + target.getRegion() + "/" + target.getVpcId()); elbGroupId = targetLookup.createSecurityGroup(upsertDescription).getSecurityGroup().getGroupId(); AmazonEC2 targetAmazonEC2 = getAmazonClientProvider().getAmazonEC2(target.getCredentials(), target.getRegion(), true); elbGroup.setTargetId(elbGroupId);
DescribeSecurityGroupsResult result = client.describeSecurityGroups(req); for (SecurityGroup group : result.getSecurityGroups()) for (IpPermission perm : group.getIpPermissions()) if (perm.getFromPort() == from && perm.getToPort() == to) ipPermissions.addAll(perm.getIpRanges()); DescribeSecurityGroupsResult result = client.describeSecurityGroups(req); for (SecurityGroup group : result.getSecurityGroups()) for (IpPermission perm : group.getIpPermissions()) if (perm.getFromPort() == from && perm.getToPort() == to) ipPermissions.addAll(perm.getIpRanges());
/** * Get a list of security group ids for the slave */ private List<String> getEc2SecurityGroups(AmazonEC2 ec2) throws AmazonClientException { List<String> groupIds = new ArrayList<String>(); DescribeSecurityGroupsResult groupResult = getSecurityGroupsBy("group-name", securityGroupSet, ec2); if (groupResult.getSecurityGroups().size() == 0) { groupResult = getSecurityGroupsBy("group-id", securityGroupSet, ec2); } for (SecurityGroup group : groupResult.getSecurityGroups()) { if (group.getVpcId() != null && !group.getVpcId().isEmpty()) { List<Filter> filters = new ArrayList<Filter>(); filters.add(new Filter("vpc-id").withValues(group.getVpcId())); filters.add(new Filter("state").withValues("available")); filters.add(new Filter("subnet-id").withValues(getCurrentSubnetId())); DescribeSubnetsRequest subnetReq = new DescribeSubnetsRequest(); subnetReq.withFilters(filters); DescribeSubnetsResult subnetResult = ec2.describeSubnets(subnetReq); List<Subnet> subnets = subnetResult.getSubnets(); if (subnets != null && !subnets.isEmpty()) { groupIds.add(group.getGroupId()); } } } if (securityGroupSet.size() != groupIds.size()) { throw new AmazonClientException("Security groups must all be VPC security groups to work in a VPC context"); } return groupIds; }
@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; }
protected String getVpcGoupId() { AmazonEC2 client = null; try { client = getEc2Client(); Filter nameFilter = new Filter().withName("group-name").withValues(config.getACLGroupName()); // SG Filter vpcFilter = new Filter().withName("vpc-id").withValues(instanceInfo.getVpcId()); DescribeSecurityGroupsRequest req = new DescribeSecurityGroupsRequest().withFilters(nameFilter, vpcFilter); DescribeSecurityGroupsResult result = client.describeSecurityGroups(req); for (SecurityGroup group : result.getSecurityGroups()) { logger.debug( "got group-id:{} for group-name:{},vpc-id:{}", group.getGroupId(), config.getACLGroupName(), instanceInfo.getVpcId()); return group.getGroupId(); } logger.error( "unable to get group-id for group-name={} vpc-id={}", config.getACLGroupName(), instanceInfo.getVpcId()); return ""; } finally { if (client != null) client.shutdown(); } }
if ((sg.getVpcId() != null && sg.getVpcId().length() > 0) || DEFAULT_SECURITY_GROUP_NAME.equals(sg.getGroupName())) { return sg.getOwnerId();
/** * Generates a list of security groups that should be applied to the target load balancer * * @param sourceDescription AWS descriptor of source load balancer * @param result result object of the calling migate operation * @return the list of security groups that will be created or added, excluding the elb-specific security group */ protected List<MigrateSecurityGroupResult> getTargetSecurityGroups(LoadBalancerDescription sourceDescription, MigrateLoadBalancerResult result) { sourceDescription.getSecurityGroups().stream() .filter(g -> !sourceLookup.getSecurityGroupById(source.getCredentialAccount(), g, source.getVpcId()).isPresent()) .forEach(m -> result.getWarnings().add("Skipping creation of security group: " + m + " (could not be found in source location)")); List<SecurityGroup> currentGroups = sourceDescription.getSecurityGroups().stream() .filter(g -> sourceLookup.getSecurityGroupById(source.getCredentialAccount(), g, source.getVpcId()).isPresent()) .map(g -> sourceLookup.getSecurityGroupById(source.getCredentialAccount(), g, source.getVpcId()) .get().getSecurityGroup()).collect(Collectors.toList()); return sourceDescription.getSecurityGroups().stream() .filter(g -> currentGroups.stream().anyMatch(g2 -> g2.getGroupId().equals(g))) .map(g -> { SecurityGroup match = currentGroups.stream().filter(g3 -> g3.getGroupId().equals(g)).findFirst().get(); SecurityGroupLocation sourceLocation = new SecurityGroupLocation(); sourceLocation.setName(match.getGroupName()); sourceLocation.setRegion(source.getRegion()); sourceLocation.setCredentials(source.getCredentials()); sourceLocation.setVpcId(source.getVpcId()); return new SecurityGroupMigrator(sourceLookup, targetLookup, migrateSecurityGroupStrategy, sourceLocation, new SecurityGroupLocation(target)).migrate(dryRun); }) .collect(Collectors.toList()); }
private Predicate<SecurityGroup> isAppSecurityGroup() { return g -> { if (!g.getGroupName().equals(applicationName)) { return false; } if (g.getVpcId() == null) { return target.getVpcId() == null; } return g.getVpcId().equals(target.getVpcId()); }; }
/** * One or more inbound rules associated with the security group. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param ipPermissions One or more inbound rules associated with the security group. * * @return A reference to this updated object so that method calls can be chained * together. */ public SecurityGroup withIpPermissions(IpPermission... ipPermissions) { if (getIpPermissions() == null) setIpPermissions(new java.util.ArrayList<IpPermission>(ipPermissions.length)); for (IpPermission value : ipPermissions) { getIpPermissions().add(value); } return this; }
/** * [EC2-VPC] One or more outbound rules associated with the security * group. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param ipPermissionsEgress [EC2-VPC] One or more outbound rules associated with the security * group. * * @return A reference to this updated object so that method calls can be chained * together. */ public SecurityGroup withIpPermissionsEgress(IpPermission... ipPermissionsEgress) { if (getIpPermissionsEgress() == null) setIpPermissionsEgress(new java.util.ArrayList<IpPermission>(ipPermissionsEgress.length)); for (IpPermission value : ipPermissionsEgress) { getIpPermissionsEgress().add(value); } return this; }
@Override protected void doScan() { rateLimit(); DescribeSecurityGroupsResult result = getClient().describeSecurityGroups(); long now = System.currentTimeMillis(); GraphNodeGarbageCollector gc = newGarbageCollector().bindScannerContext(); result.getSecurityGroups().forEach(sg -> { try { ObjectNode g = convertAwsObject(sg, getRegion()); // non-VPC security groups don't have a VPC String vpcId = Strings.nullToEmpty(sg.getVpcId()); String cypher = "merge (sg:AwsSecurityGroup {aws_arn:{arn}}) set sg+={props}, sg.updateTs={now} return sg"; JsonNode xx = getNeoRxClient() .execCypher(cypher, "arn", g.path(AWS_ARN_ATTRIBUTE).asText(), "props", g, "now", now).blockingFirst(); getShadowAttributeRemover().removeTagAttributes("AwsSecurityGroup", g, xx); gc.updateEarliestTimestamp(xx); if (!vpcId.isEmpty()) { cypher = "match (v:AwsVpc {aws_vpcId: {vpcId}}), (sg:AwsSecurityGroup {aws_arn:{sg_arn}}) merge (sg)-[:RESIDES_IN]->(v)"; getNeoRxClient().execCypher(cypher, "vpcId", vpcId, "sg_arn", g.path("aws_arn").asText()); } incrementEntityCount(); } catch (RuntimeException e) { maybeThrow(e, "problem scanning security groups"); } }); }
pair.setGroupId(targetReference.getTargetId()); pair.setGroupName(null); if (!targetGroup.getSecurityGroup().getOwnerId().equals(targetReference.getAccountId())) { pair.setVpcId(targetReference.getVpcId());