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 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; } } } }
protected void authorizeTcpAndSshIngressTraffic(String groupName) { LOG.debug("Adding a TCP ingress rule for the security group [{}].", groupName); AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest() .withFromPort(0) .withToPort(65535) .withIpProtocol("tcp") .withGroupName(groupName) .withCidrIp("0.0.0.0/0"); ec2_.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); LOG.debug("The following ingress rule was created. Security group [{}], protocol [{}] from port [{}] to port [{}] and " + "CIDR IP address [{}], region [{}]", authorizeSecurityGroupIngressRequest.getGroupName(), authorizeSecurityGroupIngressRequest.getIpProtocol(), authorizeSecurityGroupIngressRequest.getFromPort(), authorizeSecurityGroupIngressRequest.getToPort(), authorizeSecurityGroupIngressRequest.getCidrIp(), DEFAULT_API_REGION.getName()); authorizeSecurityGroupIngressRequest.withFromPort(22).withToPort(22); ec2_.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); }
/*** * 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); }
@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 ); } }
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> addInnerIngressRule(String securityGroupId) { AuthorizeSecurityGroupIngressRequest req = new AuthorizeSecurityGroupIngressRequest() .withGroupId(securityGroupId) .withIpPermissions(Collections.singletonList(buildInnerRule(securityGroupId))); String message = "Create internal Ingress Rule on AWS Security Group with id [" + securityGroupId + "]."; 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 rule already exists: %s", Utils.toString(e))); return null; } else { return e; } } }; this.client.authorizeSecurityGroupIngressAsync(req, handler); return handler.toDeferredResult() .thenApply(r -> (Void)null); }
@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."); }
public void createSGIngressRules(String securityGroupId, List<IpPermission> rules) { logger.info("create ingress sg rules, sgId={}, rules={}", securityGroupId, rules); ec2.authorizeSecurityGroupIngress(new AuthorizeSecurityGroupIngressRequest() .withGroupId(securityGroupId) .withIpPermissions(rules)); }
public void openPort(String securityGroup, int port) { IpPermission permission = new IpPermission().withIpProtocol("tcp") //$NON-NLS-1$ .withFromPort(port).withToPort(port).withIpRanges("0.0.0.0/0"); //$NON-NLS-1$ AuthorizeSecurityGroupIngressRequest request = new AuthorizeSecurityGroupIngressRequest().withGroupName(securityGroup).withIpPermissions( permission); getClient().authorizeSecurityGroupIngress(request); }
@Test public void authorizeIngressRules() { amazonEc2.setRegion(region); amazonEc2.authorizeSecurityGroupIngress(new AuthorizeSecurityGroupIngressRequest( "securityGroupName", ImmutableList.of(ipPermission(7000, "1.1.1.1/32", "2.2.2.2/32")))); replayAll(); service().authorizeIngressRules("securityGroupName", "dc1", groupPermission(7000, "1.1.1.1/32", "2.2.2.2/32")); }
private void authorizeIngressRules(AmazonEC2 client, String groupName, Set<IpPermission> ipPermissions) { if (!ipPermissions.isEmpty()) { LOG.info(">> Authorizing Security Group Ingress Rules {} for {}", ipPermissions, groupName); AuthorizeSecurityGroupIngressRequest request = new AuthorizeSecurityGroupIngressRequest() .withGroupName(groupName).withIpPermissions(ipPermissions); client.authorizeSecurityGroupIngress(request); } }
/** * Authorize SecurityGroup Ingress. * @param groupId the group id * @param ipProtocol ipProtocol for Ingress. * @param port portRange for Ingress. * @param cidrIp cidr Ip for Ingress * @return true if deleted, otherwise false. */ protected final boolean authorizeSecurityGroupIngress(final String groupId, final String ipProtocol, final Integer port, final String cidrIp) { AuthorizeSecurityGroupIngressRequest req = new AuthorizeSecurityGroupIngressRequest(); req.setGroupId(groupId); req.setCidrIp(cidrIp); req.setFromPort(port); req.setToPort(port); req.setIpProtocol(ipProtocol); AuthorizeSecurityGroupIngressResult result = amazonEC2Client.authorizeSecurityGroupIngress(req); if (result != null) { return true; } return false; }
@Override public void authorizeSecurityGroupIngress(AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest) throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
public static void main(String[] args) { final String USAGE = "To run this example, supply a group name, group description and vpc id\n" + "Ex: CreateSecurityGroup <group-name> <group-description> <vpc-id>\n"; if (args.length != 3) { System.out.println(USAGE); System.exit(1); } String group_name = args[0]; String group_desc = args[1]; String vpc_id = args[2]; final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); CreateSecurityGroupRequest create_request = new CreateSecurityGroupRequest() .withGroupName(group_name) .withDescription(group_desc) .withVpcId(vpc_id); CreateSecurityGroupResult create_response = ec2.createSecurityGroup(create_request); System.out.printf( "Successfully created security group named %s", group_name); IpRange ip_range = new IpRange() .withCidrIp("0.0.0.0/0"); IpPermission ip_perm = new IpPermission() .withIpProtocol("tcp") .withToPort(80) .withFromPort(80) .withIpv4Ranges(ip_range); IpPermission ip_perm2 = new IpPermission() .withIpProtocol("tcp") .withToPort(22) .withFromPort(22) .withIpv4Ranges(ip_range); AuthorizeSecurityGroupIngressRequest auth_request = new AuthorizeSecurityGroupIngressRequest() .withGroupName(group_name) .withIpPermissions(ip_perm, ip_perm2); AuthorizeSecurityGroupIngressResult auth_response = ec2.authorizeSecurityGroupIngress(auth_request); System.out.printf( "Successfully added ingress policy to security group %s", group_name); }
@Override public void authorizeIngress(AuthorizeSecurityGroupIngressRequest request) { authorizeIngress(request, null); }
@Override public void authorizeIngress(AuthorizeSecurityGroupIngressRequest request, ResultCapture<Void> extractor) { resource.performAction("AuthorizeIngress", request, extractor); }
@Override public void authorizeIngressRules(String groupName, String dataCenter, SecurityGroupPermission permission) { client(dataCenter).authorizeSecurityGroupIngress( new AuthorizeSecurityGroupIngressRequest(groupName, toIpPermissions(permission))); }
private void validateAndConfigureSecurityGroups(List<String> securityGroupNamesOrIds, AmazonEC2 connector, boolean withNames) throws ConnectorException { DescribeSecurityGroupsRequest describeSecurityGroupsRequest = new DescribeSecurityGroupsRequest(); if (withNames) { describeSecurityGroupsRequest.withGroupNames(securityGroupNamesOrIds); } else { describeSecurityGroupsRequest.withGroupIds(securityGroupNamesOrIds); } DescribeSecurityGroupsResult describeSecurityGroupsResult = connector.describeSecurityGroups(describeSecurityGroupsRequest); String controllerIp = "0.0.0.0/0"; int agentPort = controllerServices.getDefaultAgentPort(); // check if any one of the security group // already has agent port and controller ip List<SecurityGroup> securityGroups = describeSecurityGroupsResult.getSecurityGroups(); for (SecurityGroup securityGroup : securityGroups) { List<IpPermission> ipPermissions = securityGroup.getIpPermissions(); for (IpPermission permission : ipPermissions) { if (permission.getIpRanges().contains(controllerIp) && (agentPort >= permission.getFromPort() && agentPort <= permission.getToPort())) { return; } } } String securityGroupIdOrName = null; if (withNames) { if (securityGroupNamesOrIds.contains(Utils.DEFAULT_SECURITY_GROUP)) { securityGroupIdOrName = Utils.DEFAULT_SECURITY_GROUP; } else { securityGroupIdOrName = securityGroups.get(0).getGroupName(); } } else { securityGroupIdOrName = securityGroups.get(0).getGroupId(); } IpPermission ipPermission = new IpPermission(); ipPermission.setFromPort(agentPort); ipPermission.setToPort(agentPort); ipPermission.setIpProtocol("tcp"); ipPermission.setIpRanges(Lists.newArrayList(controllerIp)); AuthorizeSecurityGroupIngressRequest securityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest(); securityGroupIngressRequest.withIpPermissions(ipPermission); if (withNames) { securityGroupIngressRequest.withGroupName(securityGroupIdOrName); } else { securityGroupIngressRequest.withGroupId(securityGroupIdOrName); } connector.authorizeSecurityGroupIngress(securityGroupIngressRequest); }
@Test public void testCreateSecurityGroup() throws Exception { DelegateExecution execution = mock(DelegateExecution.class); final ImmutableSet<Rule> ingressRules = ImmutableSet.of( Rule.builder().anySource().icmp().createRule(), Rule.builder().anySource().port(22).tcp().createRule(), Rule.builder().anySource().port(53).udp().createRule() ); final Network network = Network.builder().ingress(ingressRules).createNetwork(); Pool pool = mock(Pool.class); when(pool.getProvider()).thenReturn(provider); when(pool.getNetwork()).thenReturn(network); when(execution.getVariable(CoreProcessVariables.POOL)).thenReturn(pool); when(execution.getProcessBusinessKey()).thenReturn(BUSINESS_KEY); activity.execute(execution); assertSecurityGroupExistsWithRules(SECURITY_GROUP_NAME, ingressRules); /* If any permissions is removed it should converge on a second run */ Set<Rule> expectedAfterRevoke = revokeAnyRule(ingressRules); assertSecurityGroupExistsWithRules(SECURITY_GROUP_NAME, expectedAfterRevoke); activity.execute(execution); assertSecurityGroupExistsWithRules(SECURITY_GROUP_NAME, ingressRules); /* If any permissions is added it should converge on a second run */ final IpPermission permission = new IpPermission().withIpProtocol("tcp") .withIpRanges("0.0.0.0/0").withFromPort(100).withToPort(120); client.authorizeSecurityGroupIngress(new AuthorizeSecurityGroupIngressRequest() .withGroupName(SECURITY_GROUP_NAME).withIpPermissions(permission)); assertSecurityGroupExistsWithRules(SECURITY_GROUP_NAME, Sets.<Rule>union(ingressRules, ImmutableSet.of(ConvertIpPermissionToRule.FUNCTION.apply(permission)))); activity.execute(execution); assertSecurityGroupExistsWithRules(SECURITY_GROUP_NAME, ingressRules); }
/** * Performs the <code>AuthorizeIngress</code> action. * * <p> * The following request parameters will be populated from the data of this * <code>SecurityGroup</code> resource, and any conflicting parameter value * set in the request will be overridden: * <ul> * <li> * <b><code>GroupId</code></b> * - mapped from the <code>Id</code> identifier. * </li> * </ul> * * <p> * * @see AuthorizeSecurityGroupIngressRequest */ void authorizeIngress(AuthorizeSecurityGroupIngressRequest request);
/** * Performs the <code>AuthorizeIngress</code> action and use a ResultCapture * to retrieve the low-level client response. * * <p> * The following request parameters will be populated from the data of this * <code>SecurityGroup</code> resource, and any conflicting parameter value * set in the request will be overridden: * <ul> * <li> * <b><code>GroupId</code></b> * - mapped from the <code>Id</code> identifier. * </li> * </ul> * * <p> * * @see AuthorizeSecurityGroupIngressRequest */ void authorizeIngress(AuthorizeSecurityGroupIngressRequest request, ResultCapture<Void> extractor);