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

The following examples show how to use com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest. 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: AWSSdkClient.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/***
 * 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);
}
 
Example #2
Source File: AmazonIpRuleManager.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@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 );
    }
}
 
Example #3
Source File: BaseTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #4
Source File: PublicAccessAutoFix.java    From pacbot with Apache License 2.0 4 votes vote down vote up
/**
 * Creates the security group.
 *
 * @param sourceSecurityGroupId the source security group id
 * @param vpcId the vpc id
 * @param ec2Client the ec 2 client
 * @param ipPermissionsToBeAdded the ip permissions to be added
 * @param resourceId the resource id
 * @param defaultCidrIp the default cidr ip
 * @param existingIpPermissions the existing ip permissions
 * @return the string
 * @throws Exception the exception
 */
public static String createSecurityGroup(String sourceSecurityGroupId, String vpcId, AmazonEC2 ec2Client, Collection<IpPermission> ipPermissionsToBeAdded, String resourceId,String defaultCidrIp,List<IpPermission> existingIpPermissions) throws Exception {
	String createdSecurityGroupId = null;
	try {
		CreateSecurityGroupRequest createsgRequest = new CreateSecurityGroupRequest();
		createsgRequest.setGroupName(createSecurityGroupName(pacTag,resourceId));
		createsgRequest.setVpcId(vpcId);
		createsgRequest.setDescription(createSecurityGroupDescription(sourceSecurityGroupId));
		CreateSecurityGroupResult createResult = ec2Client.createSecurityGroup(createsgRequest);
		createdSecurityGroupId = createResult.getGroupId();

		if (!createdSecurityGroupId.isEmpty()) {
			logger.info("Security Group {} created successfully" ,createdSecurityGroupId);
			// Authorize newly created securityGroup with Inbound Rules
			AuthorizeSecurityGroupIngressRequest authRequest = new AuthorizeSecurityGroupIngressRequest();
			authRequest.setGroupId(createdSecurityGroupId);
			if(ipPermissionsToBeAdded.isEmpty()){
                   IpRange ipv4Ranges = new IpRange();
                   ipv4Ranges.setCidrIp(defaultCidrIp);
				for (IpPermission ipPermission : existingIpPermissions) {

					if (!ipPermission.getIpv4Ranges().isEmpty()) {
						ipPermission.setIpv4Ranges(Arrays.asList(ipv4Ranges));
					}

					if (!ipPermission.getIpv6Ranges().isEmpty()) {
						Ipv6Range ipv6Range = new Ipv6Range();
						ipPermission.setIpv6Ranges(Arrays.asList(ipv6Range));
					}
					if (!ipPermission.getIpv4Ranges().isEmpty() || !ipPermission.getIpv6Ranges().isEmpty()) {
						ipPermissionsToBeAdded.add(ipPermission);
					}
				}
               }
			authRequest.setIpPermissions(ipPermissionsToBeAdded);
			ec2Client.authorizeSecurityGroupIngress(authRequest);
			//adding tag
			String deleteSgTag = CommonUtils.getPropValue("deleteSgTag");
			Map<String, String> tagMap = new HashMap();
			tagMap.put(deleteSgTag, "true");
			CreateTagsRequest createTagsRequest = new CreateTagsRequest(Arrays.asList(createdSecurityGroupId), new ArrayList<>());
			createTagsRequest.setTags(tagMap.entrySet().stream().map(t -> new Tag(t.getKey(), t.getValue())).collect(Collectors.toList()));
			try {
				ec2Client.createTags(createTagsRequest);
			} catch (AmazonServiceException ase) {
				logger.error("error tagging sg - > " + resourceId, ase);
				throw ase;
			}
		}

	} catch (Exception e) {
		logger.error(e.getMessage());
		logger.debug(e.getMessage());
		throw new RuntimeException(sourceSecurityGroupId+ " SG copy failed");
	}
	return createdSecurityGroupId;
}
 
Example #5
Source File: CreateSecurityGroup.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example #6
Source File: SecurityGroupImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public void authorizeIngress(AuthorizeSecurityGroupIngressRequest request) {
    authorizeIngress(request, null);
}
 
Example #7
Source File: SecurityGroupImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public void authorizeIngress(AuthorizeSecurityGroupIngressRequest request,
        ResultCapture<Void> extractor) {

    resource.performAction("AuthorizeIngress", request, extractor);
}
 
Example #8
Source File: EC2Application.java    From tutorials with MIT License 4 votes vote down vote up
public static void main(String[] args) {
   
    // Set up the client
    AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
        .withCredentials(new AWSStaticCredentialsProvider(credentials))
        .withRegion(Regions.US_EAST_1)
        .build();

    // Create a security group
    CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup")
        .withDescription("Baeldung Security Group");
    ec2Client.createSecurityGroup(createSecurityGroupRequest);

    // Allow HTTP and SSH traffic
    IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0");

    IpPermission ipPermission1 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
        .withIpProtocol("tcp")
        .withFromPort(80)
        .withToPort(80);

    IpPermission ipPermission2 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
        .withIpProtocol("tcp")
        .withFromPort(22)
        .withToPort(22);

    AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest()
        .withGroupName("BaeldungSecurityGroup")
        .withIpPermissions(ipPermission1, ipPermission2);

    ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);

    // Create KeyPair
    CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
        .withKeyName("baeldung-key-pair");
    CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest);
    String privateKey = createKeyPairResult
        .getKeyPair()
        .getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key

    // See what key-pairs you've got
    DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
    DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest);

    // Launch an Amazon Instance
    RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-97785bed") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html
        .withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
        .withMinCount(1)
        .withMaxCount(1)
        .withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance
        .withSecurityGroups("BaeldungSecurityGroup");

    String yourInstanceId = ec2Client.runInstances(runInstancesRequest).getReservation().getInstances().get(0).getInstanceId();

    // Start an Instance
    StartInstancesRequest startInstancesRequest = new StartInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.startInstances(startInstancesRequest);

    // Monitor Instances
    MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.monitorInstances(monitorInstancesRequest);

    UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.unmonitorInstances(unmonitorInstancesRequest);

    // Reboot an Instance

    RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.rebootInstances(rebootInstancesRequest);

    // Stop an Instance
    StopInstancesRequest stopInstancesRequest = new StopInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.stopInstances(stopInstancesRequest)
        .getStoppingInstances()
        .get(0)
        .getPreviousState()
        .getName();

    // Describe an Instance
    DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
    DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest);
    System.out.println(response.getReservations()
        .get(0)
        .getInstances()
        .get(0)
        .getKernelId());
}
 
Example #9
Source File: SecurityGroup.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * 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);
 
Example #10
Source File: SecurityGroup.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * 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);