private void createSecurityGroupByClusterName(String GROUP_NAME) { System.out.println("Creating security group for cluster "+name); CreateSecurityGroupRequest csgr = new CreateSecurityGroupRequest(); csgr.withGroupName(GROUP_NAME).withDescription("AWS Cluster toolkit security group"); CreateSecurityGroupResult createSecurityGroupResult =ec2.createSecurityGroup(csgr); IpPermission ipPermission = new IpPermission(); IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0"); ipPermission.withIpv4Ranges(Arrays.asList(new IpRange[] {ipRange1})) .withIpProtocol("tcp") .withFromPort(0) .withToPort(65535); AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest(); authorizeSecurityGroupIngressRequest.withGroupName(GROUP_NAME) .withIpPermissions(ipPermission); ec2.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); System.out.println("Created new security group "+GROUP_NAME+" with /usr/bin/ssh enabled."); }
public static String calculateIpRangeCidr(Rule rule, IpPermission ipPermission) { List<IpRange> ipv4Ranges = ipPermission.getIpv4Ranges(); List<Ipv6Range> ipv6Ranges = ipPermission.getIpv6Ranges(); if (rule.protocol.equals(Protocol.ICMPv6.getName())) { return ipv6Ranges.size() > 0 ? ipv6Ranges.get(0).getCidrIpv6() : ANY; } if (rule.protocol.equals(Protocol.ICMPv4.getName())) { // it is possible to specify Ipv6Range for IPv4 ICMP protocol return ipv4Ranges.size() > 0 ? ipv4Ranges.get(0).getCidrIp() : // in case there is no ipv4 cidr, try to obtain ipv6 one ipv6Ranges.size() > 0 ? ipv6Ranges.get(0).getCidrIpv6() : ANY; } return ipv4Ranges.size() > 0 ? ipv4Ranges.get(0).getCidrIp() : ANY; }
public void addIngressRules(String groupId, List<IpPermission> rules) { if (CollectionUtils.isNotEmpty(rules)) { AuthorizeSecurityGroupIngressRequest req = new AuthorizeSecurityGroupIngressRequest() .withGroupId(groupId).withIpPermissions(rules); try { this.client.authorizeSecurityGroupIngress(req); } catch (AmazonEC2Exception e) { if (e.getErrorCode().equals(SECURITY_GROUP_RULE_DUPLICATE)) { Utils.log(AWSUtils.class, AWSUtils.class.getSimpleName(), Level.WARNING, () -> String .format("Ingress rules already exist: %s", Utils.toString(e))); } else { throw e; } } } }
@Test public void testDefaultSecurityGroupPorts() throws Throwable { // create the group String groupId = this.client.createDefaultSecurityGroup(null); // allow the default ports this.client.addIngressRules(groupId, this.client.getDefaultRules(this.subnet)); // get the updated CM group SecurityGroup group = this.client.getDefaultSecurityGroup(null); List<IpPermission> rules = group.getIpPermissions(); assertTrue(rules.size() > 0); validateDefaultRules(rules); // lets delete the default CM group this.client.deleteSecurityGroup(groupId); }
@Test public void testAllocateSecurityGroupUpdate() throws Throwable { String groupId = this.client.createDefaultSecurityGroup(null); List<IpPermission> rules = new ArrayList<>(); IpRange ipRange = new IpRange().withCidrIp(DEFAULT_ALLOWED_NETWORK); rules.add(new IpPermission() .withIpProtocol(DEFAULT_PROTOCOL) .withFromPort(22) .withToPort(22) .withIpv4Ranges(ipRange)); this.client.addIngressRules(groupId, rules); SecurityGroup updatedGroup = this.client.getDefaultSecurityGroup(null); validateDefaultRules(updatedGroup.getIpPermissions()); this.client.deleteSecurityGroup(groupId); }
private void validateDefaultRules(List<IpPermission> rules) throws Throwable { ArrayList<Integer> ports = new ArrayList<>(); for (int port : DEFAULT_ALLOWED_PORTS) { ports.add(port); } for (IpPermission rule : rules) { assertTrue(rule.getIpProtocol().equalsIgnoreCase(DEFAULT_PROTOCOL)); if (rule.getFromPort() == 1) { assertTrue(rule.getIpv4Ranges().get(0).getCidrIp() .equalsIgnoreCase(this.subnet)); assertTrue(rule.getToPort() == 65535); } else { assertTrue(rule.getIpv4Ranges().get(0).getCidrIp() .equalsIgnoreCase(DEFAULT_ALLOWED_NETWORK)); assertEquals(rule.getFromPort(), rule.getToPort()); assertTrue(ports.contains(rule.getToPort())); } } }
/** * Gets the port range for the TCP and UDP protocols defined in the given security * group rule. If the range contains {@code -1}, it indicates all ports. * * @param permission the given security group rule * @return the port range that this security group rule applies to */ private Range<Integer> getPortRangeFromSgPermission(IpPermission permission) { Integer fromPort = permission.getFromPort(); Integer toPort = permission.getToPort(); Range<Integer> ports = null; if (fromPort != null && toPort != null) { ports = Range.closed(fromPort, toPort); } else { if (fromPort != null) { ports = Range.singleton(fromPort); } else if (toPort != null) { ports = Range.singleton(toPort); } } return ports; }
/** * Gets the IP ranges defined in the given security group rule. * * @param permission the given security group rule * @return a list of IP ranges that the security group rule applies to */ private List<String> getIpRangesFromSgPermission(IpPermission permission) { List<String> cidrs = Lists.newArrayList(); List<IpRange> ipRanges = permission.getIpv4Ranges(); if (ipRanges != null && !ipRanges.isEmpty()) { for (IpRange ipRange : ipRanges) { cidrs.add(ipRange.getCidrIp()); } } else { List<Ipv6Range> ipv6Ranges = permission.getIpv6Ranges(); if (ipv6Ranges != null && !ipv6Ranges.isEmpty()) { for (Ipv6Range ipv6Range : ipv6Ranges) { cidrs.add(ipv6Range.getCidrIpv6()); } } } return cidrs; }
@Test public void testAllTcpFromEverywhereIPv4() throws Exception { assertThat(pred).accepts( new IpPermission() .withFromPort(0) .withToPort(65535) .withIpProtocol("tcp") .withIpv4Ranges(new IpRange().withCidrIp("0.0.0.0/0"))); assertThat(pred).accepts( new IpPermission() .withFromPort(0) .withToPort(65535) .withIpProtocol("6") .withIpv4Ranges(new IpRange().withCidrIp("0.0.0.0/0"))); }
@Test public void testAllTcpFromEverywhereIPv6() throws Exception { assertThat(pred).accepts( new IpPermission() .withFromPort(0) .withToPort(65535) .withIpProtocol("tcp") .withIpv6Ranges(new Ipv6Range().withCidrIpv6("::/0"))); assertThat(pred).accepts( new IpPermission() .withFromPort(0) .withToPort(65535) .withIpProtocol("6") .withIpv6Ranges(new Ipv6Range().withCidrIpv6("::/0"))); }
@Test public void testAllUDPFromEverywhereIPv4() throws Exception { assertThat(pred).accepts( new IpPermission() .withIpProtocol("udp") .withFromPort(0) .withToPort(65535) .withIpv4Ranges(new IpRange().withCidrIp("0.0.0.0/0"))); assertThat(pred).accepts( new IpPermission() .withIpProtocol("17") .withFromPort(0) .withToPort(65535) .withIpv4Ranges(new IpRange().withCidrIp("0.0.0.0/0"))); }
@Test public void testAllUDPFromEverywhereIPv6() throws Exception { assertThat(pred).accepts( new IpPermission() .withIpProtocol("udp") .withFromPort(0) .withToPort(65535) .withIpv6Ranges(new Ipv6Range().withCidrIpv6("::/0"))); assertThat(pred).accepts( new IpPermission() .withIpProtocol("17") .withFromPort(0) .withToPort(65535) .withIpv6Ranges(new Ipv6Range().withCidrIpv6("::/0"))); }
@Test public void testAllICMPIPv6FromEverywhereIPv4() throws Exception { assertThat(pred).rejects( new IpPermission() .withIpProtocol("icmpv6") .withFromPort(-1) .withToPort(-1) .withIpv4Ranges(new IpRange().withCidrIp("0.0.0.0/0"))); assertThat(pred).rejects( new IpPermission() .withIpProtocol("58") .withFromPort(-1) .withToPort(-1) .withIpv4Ranges(new IpRange().withCidrIp("0.0.0.0/0"))); }
@Test public void testAllICMPIPv6FromEverywhereIPv6() throws Exception { assertThat(pred).rejects( new IpPermission() .withIpProtocol("icmpv6") .withFromPort(-1) .withToPort(-1) .withIpv6Ranges(new Ipv6Range().withCidrIpv6("::/0"))); assertThat(pred).rejects( new IpPermission() .withIpProtocol("58") .withFromPort(-1) .withToPort(-1) .withIpv6Ranges(new Ipv6Range().withCidrIpv6("::/0"))); }
@Test public void testAllICMPIPv4FromEverywhereIPv4() throws Exception { assertThat(pred).rejects( new IpPermission() .withIpProtocol("icmp") .withFromPort(-1) .withToPort(-1) .withIpv4Ranges(new IpRange().withCidrIp("0.0.0.0/0"))); assertThat(pred).rejects( new IpPermission() .withIpProtocol("1") .withFromPort(-1) .withToPort(-1) .withIpv4Ranges(new IpRange().withCidrIp("0.0.0.0/0"))); }
@Test public void testAllICMPIPv4FromEverywhereIPv6() throws Exception { assertThat(pred).rejects( new IpPermission() .withIpProtocol("icmp") .withFromPort(-1) .withToPort(-1) .withIpv6Ranges(new Ipv6Range().withCidrIpv6("::/0"))); assertThat(pred).rejects( new IpPermission() .withIpProtocol("1") .withFromPort(-1) .withToPort(-1) .withIpv6Ranges(new Ipv6Range().withCidrIpv6("::/0"))); }
@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); }
private String createSG(Environment env) throws Exception { String sgName = env.name + ":" + resourceId; CreateSecurityGroupRequest request = new CreateSecurityGroupRequest(sgName, sgName); if (bakeSubnet != null) request.setVpcId(bakeSubnet.getVpcId()); String sgId = AWS.ec2.createSecurityGroup(request).getGroupId(); AWS.ec2.createSGIngressRules(sgId, Lists.newArrayList(new IpPermission() .withIpv4Ranges(new IpRange().withCidrIp("0.0.0.0/0")) .withFromPort(22) .withToPort(22) .withIpProtocol("tcp"))); AWS.ec2.createTags(new CreateTagsRequest() .withResources(sgId) .withTags(tagHelper.name(resourceId), tagHelper.env(), tagHelper.resourceId(resourceId))); return sgId; }
@Override public void execute(Context context) throws Exception { List<IpPermission> permissions = new ArrayList<>(); addedIngressRules.forEach((protocol, sources) -> { IpPermission permission = new IpPermission() .withIpProtocol(protocol.ipProtocol) .withFromPort(protocol.fromPort) .withToPort(protocol.toPort); for (SecurityGroup.Source source : sources) { if (source.securityGroup != null) { permission.getUserIdGroupPairs() .add(new UserIdGroupPair().withGroupId(source.securityGroup.remoteSecurityGroup.getGroupId())); } else if (source.ipRange != null) { permission.getIpv4Ranges().add(source.ipRange); } } permissions.add(permission); }); AWS.ec2.createSGIngressRules(resource.remoteSecurityGroup.getGroupId(), permissions); }
@Test void linkDeleteSGRuleTask() { Tasks tasks = new Tasks(); SecurityGroup adminSG = new SecurityGroup("admin"); adminSG.remoteSecurityGroup = new com.amazonaws.services.ec2.model.SecurityGroup().withGroupId("admin"); SecurityGroup webSG = new SecurityGroup("web"); webSG.remoteSecurityGroup = new com.amazonaws.services.ec2.model.SecurityGroup().withGroupId("web") .withIpPermissions(new IpPermission().withUserIdGroupPairs(new UserIdGroupPair().withGroupId("admin"))); DeleteSGTask deleteAdminTask = tasks.add(new DeleteSGTask(adminSG)); DeleteSGTask deleteWebTask = tasks.add(new DeleteSGTask(webSG)); DeleteSGRuleTask deleteWebRuleTask = tasks.add(new DeleteSGRuleTask(webSG, webSG.remoteSecurityGroup.getIpPermissions())); deleteWebTask.dependsOn(deleteWebTask); new SGTaskPlanner(tasks).plan(); assertTrue(deleteAdminTask.dependencies.contains(deleteWebRuleTask)); }
/*** * Open firewall for a security group * * @param groupName Open firewall for this security group * @param ipRanges Open firewall for this IP range * @param ipProtocol Open firewall for this protocol type (eg. tcp, udp) * @param fromPort Open firewall for port range starting at this port * @param toPort Open firewall for port range ending at this port */ public void addPermissionsToSecurityGroup(String groupName, String ipRanges, String ipProtocol, Integer fromPort, Integer toPort) { final AmazonEC2 amazonEC2 = getEc2Client(); final IpPermission ipPermission = new IpPermission() .withIpRanges(ipRanges) .withIpProtocol(ipProtocol) .withFromPort(fromPort) .withToPort(toPort); final AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest() .withGroupName(groupName) .withIpPermissions(ipPermission); amazonEC2.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); LOGGER.info("Added permissions: " + ipPermission + " to security group: " + groupName); }
@Test public void testConvertTcpIpPermissionToRuleAndBack() { IpPermission expected = new IpPermission().withFromPort(1).withToPort(1024) .withIpProtocol("tcp").withIpRanges("0.0.0.0/0"); Rule rule = ConvertIpPermissionToRule.FUNCTION.apply(expected); assertNotNull(rule); assertThat(rule.getCidr()).isEqualTo("0.0.0.0/0"); assertThat(rule.getProtocol()).isEqualTo(Protocol.TCP); assertThat(rule.getPorts().lowerEndpoint()).isEqualTo(1); assertThat(rule.getPorts().upperEndpoint()).isEqualTo(1024); IpPermission actual = ConvertRuleToIpPermission.FUNCTION.apply(rule); assertThat(actual).isEqualTo(expected); }
private String createRange(IpPermission perms) { Integer to = perms.getToPort(); Integer from = perms.getFromPort(); if (to==null) { if (from==null) { return "all"; } return from.toString(); } if (to.equals(from)) { if (to.equals(-1)) { return "all"; } return to.toString(); } return String.format("%s-%s",from, to); }
@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; }
@Override public void addRules( final String name, final Collection<String> ipRanges, final String protocol, final int fromPort, final int toPort ) { IpPermission ipPermission = new IpPermission(); ipPermission.withIpRanges( ipRanges ) .withIpProtocol( protocol ) .withFromPort( fromPort ) .withToPort( toPort ); try { AuthorizeSecurityGroupIngressRequest request = new AuthorizeSecurityGroupIngressRequest(); request = request.withGroupName( name ).withIpPermissions( ipPermission ); client.authorizeSecurityGroupIngress( request ); } catch ( Exception e ) { LOG.error( "Error whilt adding rule to security group: {}", name, e ); } }
private static boolean isAllPorts(IpPermission ipPermission) { Integer minusOne = -1; if (ipPermission.getFromPort() == null && ipPermission.getToPort() == null) { return true; } if (minusOne.equals(ipPermission.getFromPort()) && minusOne.equals(ipPermission.getToPort())) { return true; } return false; }
public DeferredResult<Void> addIngressRulesAsync(String groupId, List<IpPermission> rules) { if (CollectionUtils.isNotEmpty(rules)) { AuthorizeSecurityGroupIngressRequest req = new AuthorizeSecurityGroupIngressRequest() .withGroupId(groupId).withIpPermissions(rules); String message = "Create Ingress Rules on AWS Security Group with id [" + groupId + "]."; AWSDeferredResultAsyncHandler<AuthorizeSecurityGroupIngressRequest, AuthorizeSecurityGroupIngressResult> handler = new AWSDeferredResultAsyncHandler<AuthorizeSecurityGroupIngressRequest, AuthorizeSecurityGroupIngressResult>(this.service, message) { @Override protected Exception consumeError(Exception e) { if (e instanceof AmazonEC2Exception && ((AmazonEC2Exception)e).getErrorCode().equals (SECURITY_GROUP_RULE_DUPLICATE)) { Utils.log(AWSUtils.class, AWSUtils.class.getSimpleName(), Level.WARNING, () -> String .format("Ingress rules already exist: %s", Utils.toString(e))); return null; } else { return e; } } }; this.client.authorizeSecurityGroupIngressAsync(req, handler); return handler.toDeferredResult() .thenApply(r -> (Void)null); } else { return DeferredResult.completed(null); } }
public DeferredResult<Void> removeIngressRules(String groupId, List<IpPermission> rules) { if (CollectionUtils.isNotEmpty(rules)) { RevokeSecurityGroupIngressRequest req = new RevokeSecurityGroupIngressRequest() .withGroupId(groupId).withIpPermissions(rules); String message = "Remove Ingress Rules from AWS Security Group with id [" + groupId + "]."; AWSDeferredResultAsyncHandler<RevokeSecurityGroupIngressRequest, RevokeSecurityGroupIngressResult> handler = new AWSDeferredResultAsyncHandler<RevokeSecurityGroupIngressRequest, RevokeSecurityGroupIngressResult>(this.service, message) { @Override protected Exception consumeError(Exception e) { if (e instanceof AmazonEC2Exception && ((AmazonEC2Exception)e).getErrorCode().equals (SECURITY_GROUP_RULE_NOT_FOUND)) { Utils.log(AWSUtils.class, AWSUtils.class.getSimpleName(), Level.WARNING, () -> String .format("Ingress rules cannot be removed because " + "they do not exist: %s", Utils.toString(e))); return null; } else { return e; } } }; this.client.revokeSecurityGroupIngressAsync(req, handler); return handler.toDeferredResult() .thenApply(r -> (Void)null); } else { return DeferredResult.completed(null); } }
public DeferredResult<Void> addEgressRules(String groupId, List<IpPermission> rules) { if (CollectionUtils.isNotEmpty(rules)) { AuthorizeSecurityGroupEgressRequest req = new AuthorizeSecurityGroupEgressRequest() .withGroupId(groupId).withIpPermissions(rules); String message = "Create Egress Rules on AWS Security Group with id [" + groupId + "]."; AWSDeferredResultAsyncHandler<AuthorizeSecurityGroupEgressRequest, AuthorizeSecurityGroupEgressResult> handler = new AWSDeferredResultAsyncHandler<AuthorizeSecurityGroupEgressRequest, AuthorizeSecurityGroupEgressResult>(this.service, message) { @Override protected Exception consumeError(Exception e) { if (e instanceof AmazonEC2Exception && ((AmazonEC2Exception)e).getErrorCode().equals (SECURITY_GROUP_RULE_DUPLICATE)) { Utils.log(AWSUtils.class, AWSUtils.class.getSimpleName(), Level.WARNING, () -> String .format("Egress rules already exist: %s", Utils.toString(e))); return null; } else { return e; } } }; this.client.authorizeSecurityGroupEgressAsync(req, handler); return handler.toDeferredResult() .thenApply(r -> (Void)null); } else { return DeferredResult.completed(null); } }
public DeferredResult<Void> removeEgressRules(String groupId, List<IpPermission> rules) { if (CollectionUtils.isNotEmpty(rules)) { RevokeSecurityGroupEgressRequest req = new RevokeSecurityGroupEgressRequest() .withGroupId(groupId).withIpPermissions(rules); String message = "Remove Egress Rules from AWS Security Group with id [" + groupId + "]."; AWSDeferredResultAsyncHandler<RevokeSecurityGroupEgressRequest, RevokeSecurityGroupEgressResult> handler = new AWSDeferredResultAsyncHandler<RevokeSecurityGroupEgressRequest, RevokeSecurityGroupEgressResult>(this.service, message) { @Override protected Exception consumeError(Exception e) { if (e instanceof AmazonEC2Exception && ((AmazonEC2Exception)e).getErrorCode().equals (SECURITY_GROUP_RULE_NOT_FOUND)) { Utils.log(AWSUtils.class, AWSUtils.class.getSimpleName(), Level.WARNING, () -> String .format("Egress rules cannot be removed because " + "they do not exist: %s", Utils.toString(e))); return null; } else { return e; } } }; this.client.revokeSecurityGroupEgressAsync(req, handler); return handler.toDeferredResult() .thenApply(r -> (Void)null); } else { return DeferredResult.completed(null); } }
public List<IpPermission> getDefaultRules(String subnet) { List<IpPermission> rules = new ArrayList<>(); for (int port : DEFAULT_ALLOWED_PORTS) { if (port > 1) { rules.add(createRule(port)); } else { rules.add(createRule(1, 65535, subnet, DEFAULT_PROTOCOL)); } } return rules; }
private IpPermission createRule(int fromPort, int toPort, String subnet, String protocol) { IpRange ipRange = new IpRange().withCidrIp(subnet); protocol = protocol.equals(ALL_TRAFFIC) ? ALL_PROTOCOLS : protocol; return new IpPermission() .withIpProtocol(protocol) .withFromPort(fromPort) .withToPort(toPort) .withIpv4Ranges(ipRange); }
private IpPermission buildInnerRule(String securityGroupId) { return new IpPermission() .withIpProtocol(ALL_PROTOCOLS) .withUserIdGroupPairs(Collections.singletonList( new UserIdGroupPair() .withGroupId(securityGroupId) )); }
@Test public void testBuildRules() throws Throwable { ArrayList<Rule> rules = TestUtils.getAllowIngressRules(); List<IpPermission> awsRules = this.client.buildRules(rules); for (IpPermission rule : awsRules) { assertDefaultRules(rule); } }
@Test public void testUpdateIngressRules() throws Throwable { String groupID = this.client.createDefaultSecurityGroup(null); ArrayList<Rule> rules = TestUtils.getAllowIngressRules(); this.client.addIngressRules(groupID, this.client.buildRules(rules)); SecurityGroup awsSG = this.client.getSecurityGroupById(groupID); List<IpPermission> ingress = awsSG.getIpPermissions(); for (IpPermission rule : ingress) { assertDefaultRules(rule); } this.client.deleteSecurityGroup(groupID); }
@Override public void run(final WhitelistCidrForVpcAccessCommand command) { final BaseOutputs baseStackOutputs = configStore.getBaseStackOutputs(); logger.info("Revoking the previous ingress rules..."); final DescribeSecurityGroupsResult securityGroupsResult = ec2Client.describeSecurityGroups( new DescribeSecurityGroupsRequest().withGroupIds(baseStackOutputs.getToolsIngressSgId())); securityGroupsResult.getSecurityGroups().forEach(securityGroup -> { if (!securityGroup.getIpPermissions().isEmpty()) { RevokeSecurityGroupIngressRequest revokeIngressRequest = new RevokeSecurityGroupIngressRequest() .withGroupId(baseStackOutputs.getToolsIngressSgId()) .withIpPermissions(securityGroup.getIpPermissions()); ec2Client.revokeSecurityGroupIngress(revokeIngressRequest); } }); logger.info("Done."); logger.info("Authorizing the new ingress rules..."); final List<IpPermission> ipPermissionList = Lists.newArrayListWithCapacity(command.getPorts().size()); command.getPorts().forEach(port -> { IpPermission ipPermission = new IpPermission() .withIpRanges(command.getCidrs()) .withIpProtocol("tcp") .withFromPort(port) .withToPort(port); ipPermissionList.add(ipPermission); }); AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest() .withGroupId(baseStackOutputs.getToolsIngressSgId()) .withIpPermissions(ipPermissionList); ec2Client.authorizeSecurityGroupIngress(ingressRequest); logger.info("Done."); }
private static boolean hasExternalSource(final IpPermission rule) { final boolean hasExternalIpv4Range = rule.getIpv4Ranges().stream() .map(IpRange::getCidrIp) .map(Ipv4Range::parseCidr) .anyMatch(range -> PRIVATE_IPV4_RANGES.stream().noneMatch(privateRange -> privateRange.contains(range))); final boolean hasExternalIpv6Ranges = rule.getIpv6Ranges().stream() .map(com.amazonaws.services.ec2.model.Ipv6Range::getCidrIpv6) .map(Ipv6Range::parseCidr) .anyMatch(range -> !PRIVATE_IPV6_RANGE.contains(range)); return hasExternalIpv4Range || hasExternalIpv6Ranges; }
@SuppressWarnings({"SimplifiableIfStatement"}) private static boolean opensUnallowedPorts(final IpPermission rule, final Set<Integer> allowedPorts) { final String protocol = rule.getIpProtocol(); if (protocol != null) { // match logical names as well as protocol numbers switch (protocol.toLowerCase()) { case "tcp": case "6": case "udp": case "17": // check port ranges break; case "icmp": case "1": case "icmpv6": case "58": return false; default: // From http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_IpPermission.html // [...] specifying -1 or a protocol number other than tcp, udp, icmp, or 58 (ICMPv6) // allows traffic on all ports, regardless of any port range you specify. [...] return true; } } final Integer fromPort = rule.getFromPort(); final Integer toPort = rule.getToPort(); // No port range means: All traffic if (fromPort == null || toPort == null) { return true; } // Is there at least one non-allowed port? return IntStream.rangeClosed(fromPort, toPort).anyMatch(port -> !allowedPorts.contains(port)); }
@Test public void testAllTrafficFromSecurityGroups() throws Exception { assertThat(pred).rejects( new IpPermission() .withIpProtocol("-1") .withUserIdGroupPairs( new UserIdGroupPair().withUserId("111222333444").withGroupId("sg-11223344"))); }
@Test public void testAllTrafficFromPrivateNetworks() throws Exception { assertThat(pred).rejects( new IpPermission() .withIpProtocol("-1") .withIpv4Ranges( new IpRange().withCidrIp("10.0.0.0/8"), new IpRange().withCidrIp("172.31.0.0/16"), new IpRange().withCidrIp("172.16.0.0/12"), new IpRange().withCidrIp("192.168.0.0/16")) .withIpv6Ranges( new Ipv6Range().withCidrIpv6("fc00::/7")) ); }