Java Code Examples for org.jclouds.net.domain.IpProtocol

The following examples show how to use org.jclouds.net.domain.IpProtocol. These examples are extracted from open source projects. 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 Project: karamel   Source File: NovaLauncherTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void createSecurityGroupTestWithTestingFlag() throws KaramelException {
  //Initializing and mocking need for method test
  SecurityGroupRule rule = mock(SecurityGroupRule.class);
  String uniqueGroup = NovaSetting.NOVA_UNIQUE_GROUP_NAME(clusterName, groupName);
  String uniqueDescription = NovaSetting.NOVA_UNIQUE_GROUP_DESCRIPTION(clusterName, groupName);

  Ingress ingress = Ingress.builder()
          .fromPort(0)
          .toPort(65535)
          .ipProtocol(IpProtocol.TCP)
          .build();

  when(novaContext.getSecurityGroupApi()).thenReturn(securityGroupApi);
  when(securityGroupApi.createWithDescription(uniqueGroup, uniqueDescription)).thenReturn(securityGroupCreated);
  when(securityGroupCreated.getId()).thenReturn("10");
  when(securityGroupApi.createRuleAllowingCidrBlock("10", ingress, "0.0.0.0/0")).thenReturn(rule);

  NovaLauncher novaLauncher = new NovaLauncher(novaContext, sshKeyPair);
  String groupId = novaLauncher.createSecurityGroup(clusterName, groupName, nova, ports);
  assertEquals("10", groupId);
}
 
Example 2
Source Project: brooklyn-server   Source File: NetworkingEffectors.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Collection<SecurityGroup> call(ConfigBag parameters) {
    List<String> rawPortRules = parameters.get(INBOUND_PORTS_LIST);
    IpProtocol ipProtocol = parameters.get(INBOUND_PORTS_LIST_PROTOCOL);
    Preconditions.checkNotNull(ipProtocol, INBOUND_PORTS_LIST_PROTOCOL.getName() + " cannot be null");
    Preconditions.checkNotNull(rawPortRules, INBOUND_PORTS_LIST.getName() + " cannot be null");

    SharedLocationSecurityGroupCustomizer locationSecurityGroupCustomizer = new SharedLocationSecurityGroupCustomizer();
    if (IpProtocol.TCP.equals(ipProtocol)) {
        locationSecurityGroupCustomizer.setTcpPortRanges(rawPortRules);
    } else if (IpProtocol.UDP.equals(ipProtocol)) {
        locationSecurityGroupCustomizer.setUdpPortRanges(rawPortRules);
    } else if (IpProtocol.ICMP.equals(ipProtocol)) {
        locationSecurityGroupCustomizer.setOpenIcmp(true);
    }

    Optional<Location> jcloudsMachineLocationOptional = tryFind(
            (Iterable<Location>) getLocationsCheckingAncestors(null, entity()),
            instanceOf(JcloudsMachineLocation.class));
    if (!jcloudsMachineLocationOptional.isPresent()) {
        throw new IllegalArgumentException("Tried to execute open ports effector on an entity with no JcloudsMachineLocation");
    }
    JcloudsLocation jcloudsLocation = ((JcloudsMachineLocation)jcloudsMachineLocationOptional.get()).getParent();

    return locationSecurityGroupCustomizer.applySecurityGroupCustomizations(jcloudsLocation, jcloudsLocation.getComputeService(),(JcloudsMachineLocation)jcloudsMachineLocationOptional.get());
}
 
Example 3
Source Project: attic-stratos   Source File: AWSSecurityGroupApiTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testAuthorizeSecurityGroupIpPermissions() throws SecurityException, NoSuchMethodException, IOException {
   Invokable<?, ?> method = method(AWSSecurityGroupApi.class, "authorizeSecurityGroupIngressInRegion",
         String.class, String.class, Iterable.class);
   GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "group", ImmutableSet.<IpPermission> of(IpPermissions
         .permit(IpProtocol.TCP).originatingFromCidrBlock("1.1.1.1/32"), IpPermissions.permitICMP().type(8).andCode(0)
         .originatingFromSecurityGroupId("groupId"))));

   assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
   assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
   assertPayloadEquals(
         request,
         "Action=AuthorizeSecurityGroupIngress&GroupId=group&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=1&IpPermissions.0.ToPort=65535&IpPermissions.0.IpRanges.0.CidrIp=1.1.1.1/32&IpPermissions.1.IpProtocol=icmp&IpPermissions.1.FromPort=8&IpPermissions.1.ToPort=0&IpPermissions.1.Groups.0.GroupId=groupId",
         "application/x-www-form-urlencoded", false);

   assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
   assertSaxResponseParserClassEquals(method, null);
   assertFallbackClassEquals(method, null);

   checkFilters(request);
}
 
Example 4
Source Project: attic-stratos   Source File: AWSSecurityGroupApiTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testRevokeSecurityGroupIpPermissions() throws SecurityException, NoSuchMethodException, IOException {
   Invokable<?, ?> method = method(AWSSecurityGroupApi.class, "revokeSecurityGroupIngressInRegion", String.class,
         String.class, Iterable.class);
   GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "group", ImmutableSet.<IpPermission> of(IpPermissions
         .permit(IpProtocol.TCP).originatingFromCidrBlock("1.1.1.1/32"), IpPermissions.permitICMP().type(8).andCode(0)
         .originatingFromSecurityGroupId("groupId"))));

   assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
   assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
   assertPayloadEquals(
         request,
         "Action=RevokeSecurityGroupIngress&GroupId=group&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=1&IpPermissions.0.ToPort=65535&IpPermissions.0.IpRanges.0.CidrIp=1.1.1.1/32&IpPermissions.1.IpProtocol=icmp&IpPermissions.1.FromPort=8&IpPermissions.1.ToPort=0&IpPermissions.1.Groups.0.GroupId=groupId",
         "application/x-www-form-urlencoded", false);

   assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
   assertSaxResponseParserClassEquals(method, null);
   assertFallbackClassEquals(method, null);

   checkFilters(request);
}
 
Example 5
public Set<SecurityGroup> expected() {
      return ImmutableSet.of(SecurityGroup.builder()
                                          .region(defaultRegion)
                                          .ownerId("123123123123")
                                          .id("sg-11111111")
                                          .name("default")
                                          .description("default VPC security group")
//                                          .vpcId("vpc-99999999")
                                          .ipPermission(IpPermission.builder()
                                                                    .ipProtocol(IpProtocol.ALL)
                                                                    .tenantIdGroupNamePair("123123123123", "sg-11111111").build())
//                                          .ipPermissionEgress(IpPermission.builder()
//                                                                    .ipProtocol(IpProtocol.ALL)
//                                                                    .ipRange("0.0.0.0/0").build())
                                          .build());

   }
 
Example 6
Source Project: karamel   Source File: NovaLauncherTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testForkGroup() throws KaramelException{
  //Same test parameters as the securityGroup Test
  //Initializing and mocking need for method test
  SecurityGroupRule rule = mock(SecurityGroupRule.class);
  String uniqueGroup = NovaSetting.NOVA_UNIQUE_GROUP_NAME(clusterName, groupName);
  String uniqueDescription = NovaSetting.NOVA_UNIQUE_GROUP_DESCRIPTION(clusterName, groupName);

  Ingress ingress = Ingress.builder()
          .fromPort(0)
          .toPort(65535)
          .ipProtocol(IpProtocol.TCP)
          .build();

  when(novaContext.getSecurityGroupApi()).thenReturn(securityGroupApi);
  when(securityGroupApi.createWithDescription(uniqueGroup, uniqueDescription)).thenReturn(securityGroupCreated);
  when(securityGroupCreated.getId()).thenReturn("10");
  when(securityGroupApi.createRuleAllowingCidrBlock("10", ingress, "0.0.0.0/0")).thenReturn(rule);

  NovaLauncher novaLauncher = new NovaLauncher(novaContext, sshKeyPair);
  //String groupId = novaLauncher.createSecurityGroup(clusterName, groupName, nova, ports);

  JsonCluster cluster = mock(JsonCluster.class);
  ClusterRuntime clusterRuntime = mock(ClusterRuntime.class);
  List<JsonGroup> groups = new ArrayList<>();
  JsonGroup group = mock(JsonGroup.class);
  groups.add(group);
  when(group.getName()).thenReturn(groupName);
  when(cluster.getGroups()).thenReturn(groups);
  when(group.getProvider()).thenReturn(nova);
  when(cluster.getProvider()).thenReturn(nova);
  when(cluster.getName()).thenReturn(clusterName);
  String groupId = novaLauncher.forkGroup(cluster,clusterRuntime,groupName);

  assertEquals("10", groupId);
}
 
Example 7
Source Project: brooklyn-library   Source File: RiakNodeImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void configureInternalNetworking() {
    Location location = getDriver().getLocation();
    if (!(location instanceof JcloudsSshMachineLocation)) {
        LOG.info("Not running in a JcloudsSshMachineLocation, not adding IP permissions to {}", this);
        return;
    }
    JcloudsMachineLocation machine = (JcloudsMachineLocation) location;
    JcloudsLocationSecurityGroupCustomizer customizer = JcloudsLocationSecurityGroupCustomizer.getInstance(getApplicationId());

    String cidr = Cidr.UNIVERSAL.toString(); // TODO configure with a more restrictive CIDR
    Collection<IpPermission> permissions = MutableList.<IpPermission>builder()
            .add(IpPermission.builder()
                    .ipProtocol(IpProtocol.TCP)
                    .fromPort(sensors().get(ERLANG_PORT_RANGE_START))
                    .toPort(sensors().get(ERLANG_PORT_RANGE_END))
                    .cidrBlock(cidr)
                    .build())
            .add(IpPermission.builder()
                    .ipProtocol(IpProtocol.TCP)
                    .fromPort(config().get(HANDOFF_LISTENER_PORT))
                    .toPort(config().get(HANDOFF_LISTENER_PORT))
                    .cidrBlock(cidr)
                    .build())
            .add(IpPermission.builder()
                    .ipProtocol(IpProtocol.TCP)
                    .fromPort(config().get(EPMD_LISTENER_PORT))
                    .toPort(config().get(EPMD_LISTENER_PORT))
                    .cidrBlock(cidr)
                    .build())
             .build();
    LOG.debug("Applying custom security groups to {}: {}", machine, permissions);
    customizer.addPermissionsToLocation(machine, permissions);
}
 
Example 8
/**
 * Creates a security group with rules to:
 * <ul>
 *     <li>Allow SSH access on port 22 from the world</li>
 *     <li>Allow TCP, UDP and ICMP communication between machines in the same group</li>
 * </ul>
 *
 * It needs to consider locationId as port ranges and groupId are cloud provider-dependent e.g openstack nova
 * wants from 1-65535 while aws-ec2 accepts from 0-65535.
 *
 *
 * @param groupName The name of the security group to create
 * @param securityApi The API to use to create the security group
 *
 * @return the created security group
 */
private SecurityGroup createBaseSecurityGroupInLocation(String groupName,
        SecurityGroupEditor groupEditor) {

    SecurityGroup group = groupEditor.createSecurityGroup(groupName);

    String groupId = group.getProviderId();
    int fromPort = 0;
    if (isOpenstackNova(groupEditor.getLocation())) {
        groupId = group.getId();
        fromPort = 1;
    }
    // Note: For groupName to work with GCE we also need to tag the machines with the same ID.
    // See sourceTags section at https://developers.google.com/compute/docs/networking#firewalls
    IpPermission.Builder allWithinGroup = IpPermission.builder()
            .groupId(groupId)
            .fromPort(fromPort)
            .toPort(65535);
    group = groupEditor.addPermission(group, allWithinGroup.ipProtocol(IpProtocol.TCP).build());
    group = groupEditor.addPermission(group, allWithinGroup.ipProtocol(IpProtocol.UDP).build());
    if (!isAzure(groupEditor.getLocation())) {
        group = groupEditor.addPermission(group,
            allWithinGroup.ipProtocol(IpProtocol.ICMP).fromPort(-1).toPort(-1).build());
    }

    IpPermission sshPermission = IpPermission.builder()
            .fromPort(22)
            .toPort(22)
            .ipProtocol(IpProtocol.TCP)
            .cidrBlock(getBrooklynCidrBlock())
            .build();
    group = groupEditor.addPermission(group, sshPermission);

    return group;
}
 
Example 9
public Collection<SecurityGroup> applySecurityGroupCustomizations(JcloudsLocation location, ComputeService computeService, JcloudsMachineLocation machine) {
    super.customize(location, computeService, machine);

    if(!enabled) return ImmutableList.of();

    final JcloudsLocationSecurityGroupCustomizer instance = getInstance(getSharedGroupId(location));

    ImmutableList.Builder<IpPermission> builder = ImmutableList.<IpPermission>builder();

    builder.addAll(getIpPermissions(instance, tcpPortRanges, IpProtocol.TCP));
    builder.addAll(getIpPermissions(instance, udpPortRanges, IpProtocol.UDP));
    if (Boolean.TRUE.equals(openIcmp)) {
        builder.addAll(ImmutableList.of(
                IpPermission
                        .builder().ipProtocol(IpProtocol.ICMP).fromPort(-1).toPort(-1)
                        .cidrBlock(instance.getBrooklynCidrBlock())
                        .build()));
    }

    if (inboundPorts != null) {
        for (int inboundPort : inboundPorts) {
            IpPermission ipPermission = IpPermission.builder()
                    .fromPort(inboundPort)
                    .toPort(inboundPort)
                    .ipProtocol(IpProtocol.TCP)
                    .cidrBlock(instance.getBrooklynCidrBlock())
                    .build();
            builder.add(ipPermission);
        }
    }
    return instance.addPermissionsToLocationAndReturnSecurityGroup(machine, builder.build());
}
 
Example 10
private List<IpPermission> getIpPermissions(JcloudsLocationSecurityGroupCustomizer instance, RangeSet<Integer> portRanges, IpProtocol protocol) {
    List<IpPermission> ipPermissions = ImmutableList.<IpPermission>of();
    if (portRanges != null) {
         ipPermissions =
                FluentIterable
                        .from(portRanges.asRanges())
                        .transform(portRangeToPermission(instance, protocol))
                        .toList();
    }
    return ipPermissions;
}
 
Example 11
private Function<Range<Integer>, IpPermission> portRangeToPermission(final JcloudsLocationSecurityGroupCustomizer instance, final IpProtocol protocol) {
    return new Function<Range<Integer>, IpPermission>() {
        @Nullable
        @Override
        public IpPermission apply(@Nullable Range<Integer> integerRange) {
            IpPermission extraPermission = IpPermission.builder()
                    .fromPort(integerRange.lowerEndpoint())
                    .toPort(integerRange.upperEndpoint())
                    .ipProtocol(protocol)
                    .cidrBlock(instance.getBrooklynCidrBlock())
                    .build();
            return extraPermission;
        }
    };
}
 
Example 12
private IpPermission aPermission() {
    return IpPermission.builder()
        .ipProtocol(IpProtocol.TCP)
        .fromPort(22)
        .toPort(22)
        .cidrBlock("0.0.0.0/0")
        .build();
}
 
Example 13
private IpPermission newPermission(int port) {
    return IpPermission.builder()
            .ipProtocol(IpProtocol.TCP)
            .fromPort(port)
            .toPort(port)
            .cidrBlock("0.0.0.0/0")
            .build();
}
 
Example 14
@Test
public void testPermissionsSetFromPortRanges() {
    customizer.setTcpPortRanges(ImmutableList.of("99-100"));
    when(sgCustomizer.getBrooklynCidrBlock()).thenReturn("10.10.10.10/24");
    customizer.customize(jcloudsLocation, computeService, mock(JcloudsMachineLocation.class));
    assertPermissionsAdded(99, 100, IpProtocol.TCP);
}
 
Example 15
@Test
public void testUdpPermissionsSetFromPortRanges() {
    customizer.setUdpPortRanges(ImmutableList.of("55-78"));
    when(sgCustomizer.getBrooklynCidrBlock()).thenReturn("10.10.10.10/24");
    customizer.customize(jcloudsLocation, computeService, mock(JcloudsMachineLocation.class));
    assertPermissionsAdded(55, 78, IpProtocol.UDP);
}
 
Example 16
@Test
public void testInboundIcmpAddedToPermissions() {
    customizer.setOpenIcmp(true);
    when(sgCustomizer.getBrooklynCidrBlock()).thenReturn(Cidr.UNIVERSAL.toString());
    customizer.customize(jcloudsLocation, computeService, mock(JcloudsMachineLocation.class));
    assertPermissionsAdded(-1, -1, IpProtocol.ICMP);
}
 
Example 17
@Test
public void testInboundPortsAddedToPermissions() {
    when(mockOptions.getInboundPorts()).thenReturn(new int[]{5});
    when(sgCustomizer.getBrooklynCidrBlock()).thenReturn("10.10.10.10/24");
    customizer.customize(jcloudsLocation, computeService, mockTemplate);
    customizer.customize(jcloudsLocation, computeService, mock(JcloudsMachineLocation.class));
    assertPermissionsAdded(5, 5, IpProtocol.TCP);
}
 
Example 18
private void assertPermissionsAdded(int expectedFrom, int expectedTo, IpProtocol expectedProtocol) {
    ArgumentCaptor<List> listArgumentCaptor = ArgumentCaptor.forClass(List.class);
    verify(sgCustomizer).addPermissionsToLocationAndReturnSecurityGroup(any(JcloudsMachineLocation.class), listArgumentCaptor.capture());
    IpPermission ipPermission = (IpPermission) listArgumentCaptor.getValue().get(0);
    assertEquals(ipPermission.getFromPort(), expectedFrom);
    assertEquals(ipPermission.getToPort(), expectedTo);
    assertEquals(ipPermission.getIpProtocol(), expectedProtocol);
}
 
Example 19
protected Predicate<SecurityGroup> ruleExistsPredicate(final int fromPort, final int toPort, final IpProtocol ipProtocol) {
    return new Predicate<SecurityGroup>() {
        @Override
        public boolean apply(SecurityGroup scipPermission) {
            for (IpPermission ipPermission : scipPermission.getIpPermissions()) {
                if (ipPermission.getFromPort() == fromPort && ipPermission.getToPort() == toPort && ipPermission.getIpProtocol() == ipProtocol) {
                    return true;
                }
            }
            return false;
        }
    };
}
 
Example 20
@Override
public SecurityGroup addIpPermission(IpProtocol protocol, int startPort, int endPort,
                                     Multimap<String, String> tenantIdGroupNamePairs,
                                     Iterable<String> ipRanges,
                                     Iterable<String> groupIds, SecurityGroup group) {
   String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());
   String id = group.getProviderId();

   IpPermission.Builder builder = IpPermission.builder();

   builder.ipProtocol(protocol);
   builder.fromPort(startPort);
   builder.toPort(endPort);

   if (!Iterables.isEmpty(ipRanges)) {
      for (String cidr : ipRanges) {
         builder.cidrBlock(cidr);
      }
   }

   if (!tenantIdGroupNamePairs.isEmpty()) {
      for (String userId : tenantIdGroupNamePairs.keySet()) {
         for (String groupString : tenantIdGroupNamePairs.get(userId)) {
            String[] parts = AWSUtils.parseHandle(groupString);
            String groupId = parts[1];
            builder.tenantIdGroupNamePair(userId, groupId);
         }
      }
   }

   client.getSecurityGroupApi().get().authorizeSecurityGroupIngressInRegion(region, id, builder.build());

   return getSecurityGroupById(group.getId());
}
 
Example 21
@Override
public SecurityGroup removeIpPermission(IpProtocol protocol, int startPort, int endPort,
                                        Multimap<String, String> tenantIdGroupNamePairs,
                                        Iterable<String> ipRanges,
                                        Iterable<String> groupIds, SecurityGroup group) {
   String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());
   String id = group.getProviderId();

   IpPermission.Builder builder = IpPermission.builder();

   builder.ipProtocol(protocol);
   builder.fromPort(startPort);
   builder.toPort(endPort);

   if (!Iterables.isEmpty(ipRanges)) {
      for (String cidr : ipRanges) {
         builder.cidrBlock(cidr);
      }
   }

   if (!tenantIdGroupNamePairs.isEmpty()) {
      for (String userId : tenantIdGroupNamePairs.keySet()) {
         for (String groupString : tenantIdGroupNamePairs.get(userId)) {
            String[] parts = AWSUtils.parseHandle(groupString);
            String groupId = parts[1];
            builder.tenantIdGroupNamePair(userId, groupId);
         }
      }
   }

   client.getSecurityGroupApi().get().revokeSecurityGroupIngressInRegion(region, id, builder.build());

   return getSecurityGroupById(group.getId());
}
 
Example 22
Source Project: attic-stratos   Source File: AWSEC2IpPermissionHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void endElement(String uri, String name, String qName) throws SAXException {
   if (equalsOrSuffix(qName, "ipProtocol")) {
      // Algorete: ipProtocol can be an empty tag on EC2 clone (e.g.
      // OpenStack EC2)
      builder.ipProtocol(IpProtocol.fromValue(currentOrNegative(currentText)));
   } else if (equalsOrSuffix(qName, "fromPort")) {
      // Algorete: fromPort can be an empty tag on EC2 clone (e.g. OpenStack
      // EC2)
      builder.fromPort(Integer.parseInt(currentOrNegative(currentText)));
   } else if (equalsOrSuffix(qName, "toPort")) {
      // Algorete: toPort can be an empty tag on EC2 clone (e.g. OpenStack
      // EC2)
      builder.toPort(Integer.parseInt(currentOrNegative(currentText)));
   } else if (equalsOrSuffix(qName, "cidrIp")) {
      builder.cidrBlock(currentOrNull(currentText));
   } else if (equalsOrSuffix(qName, "userId")) {
      this.userId = currentOrNull(currentText);
   } else if (equalsOrSuffix(qName, "groupId")) {
      this.groupId = currentOrNull(currentText);
   } else if (equalsOrSuffix(qName, "item")) {
      if (userId != null && groupId != null)
         builder.tenantIdGroupNamePair(userId, groupId);
      userId = groupId = null;
   }
   currentText.setLength(0);
}
 
Example 23
Source Project: attic-stratos   Source File: AWSSecurityGroupApiLiveTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testAuthorizeSecurityGroupIngressSourceGroup() {
   final String group1Name = PREFIX + "ingress1";
   String group2Name = PREFIX + "ingress2";
   cleanupAndSleep(group2Name);
   cleanupAndSleep(group1Name);
   try {
      final String group1Id = AWSSecurityGroupApi.class.cast(client).createSecurityGroupInRegionAndReturnId(null,
              group1Name, group1Name);
      String group2Id = AWSSecurityGroupApi.class.cast(client).createSecurityGroupInRegionAndReturnId(null,
              group2Name, group2Name);
      ensureGroupsExist(group1Name, group2Name);
      client.authorizeSecurityGroupIngressInRegion(null, group1Name, IpProtocol.TCP, 80, 80, "0.0.0.0/0");
      assertEventually(new GroupHasPermission(client, group1Name, new TCPPort80AllIPs()));
      Set<SecurityGroup> oneResult = client.describeSecurityGroupsInRegion(null, group1Name);
      assertNotNull(oneResult);
      assertEquals(oneResult.size(), 1);
      final SecurityGroup group = oneResult.iterator().next();
      assertEquals(group.getName(), group1Name);
      final UserIdGroupPair to = new UserIdGroupPair(group.getOwnerId(), group1Name);
      client.authorizeSecurityGroupIngressInRegion(null, group2Name, to);
      assertEventually(new GroupHasPermission(client, group2Name, new Predicate<IpPermission>() {
         @Override
         public boolean apply(IpPermission arg0) {
            return arg0.getTenantIdGroupNamePairs().equals(ImmutableMultimap.of(group.getOwnerId(), group1Id));
         }
      }));

      client.revokeSecurityGroupIngressInRegion(null, group2Name,
              new UserIdGroupPair(group.getOwnerId(), group1Name));
      assertEventually(new GroupHasNoPermissions(client, group2Name));
   } finally {
      client.deleteSecurityGroupInRegion(null, group2Name);
      client.deleteSecurityGroupInRegion(null, group1Name);
   }
}
 
Example 24
Source Project: karamel   Source File: Ec2Launcher.java    License: Apache License 2.0 4 votes vote down vote up
public String createSecurityGroup(String clusterName, String groupName, Ec2 ec2, Set<String> ports)
    throws KaramelException {
  String uniqeGroupName = Settings.AWS_UNIQUE_GROUP_NAME(clusterName, groupName);
  logger.info(String.format("Creating security group '%s' ...", uniqeGroupName));
  if (context == null) {
    throw new KaramelException("Register your valid credentials first :-| ");
  }

  if (sshKeyPair == null) {
    throw new KaramelException("Choose your ssh keypair first :-| ");
  }

  Optional<? extends org.jclouds.ec2.features.SecurityGroupApi> securityGroupExt
      = context.getEc2api().getSecurityGroupApiForRegion(ec2.getRegion());
  if (securityGroupExt.isPresent()) {
    AWSSecurityGroupApi client = (AWSSecurityGroupApi) securityGroupExt.get();
    String groupId = null;
    if (ec2.getVpc() != null) {
      CreateSecurityGroupOptions csgos = CreateSecurityGroupOptions.Builder.vpcId(ec2.getVpc());
      groupId = client.createSecurityGroupInRegionAndReturnId(ec2.getRegion(), uniqeGroupName, uniqeGroupName, csgos);
    } else {
      groupId = client.createSecurityGroupInRegionAndReturnId(ec2.getRegion(), uniqeGroupName, uniqeGroupName);
    }

    if (!TESTING) {
      for (String port : ports) {
        Integer p = null;
        IpProtocol pr = null;
        if (port.contains("/")) {
          String[] s = port.split("/");
          p = Integer.valueOf(s[0]);
          pr = IpProtocol.valueOf(s[1]);
        } else {
          p = Integer.valueOf(port);
          pr = IpProtocol.TCP;
        }
        client.authorizeSecurityGroupIngressInRegion(ec2.getRegion(),
            uniqeGroupName, pr, p, Integer.valueOf(port), "0.0.0.0/0");
        logger.info(String.format("Ports became open for '%s'", uniqeGroupName));
      }
    } else {
      IpPermission tcpPerms = IpPermission.builder().ipProtocol(IpProtocol.TCP).
          fromPort(0).toPort(65535).cidrBlock("0.0.0.0/0").build();
      IpPermission udpPerms = IpPermission.builder().ipProtocol(IpProtocol.UDP).
          fromPort(0).toPort(65535).cidrBlock("0.0.0.0/0").build();
      ArrayList<IpPermission> perms = Lists.newArrayList(tcpPerms, udpPerms);
      client.authorizeSecurityGroupIngressInRegion(ec2.getRegion(), groupId, perms);
      logger.info(String.format("Ports became open for '%s'", uniqeGroupName));
    }
    logger.info(String.format("Security group '%s' was created :)", uniqeGroupName));
    return groupId;
  }
  return null;
}
 
Example 25
Source Project: brooklyn-server   Source File: SecurityGroupDefinition.java    License: Apache License 2.0 4 votes vote down vote up
/** allows access to the given port on TCP from within the subnet */
public SecurityGroupDefinition allowingInternalPort(int port) {
    return allowing(IpPermissions.permit(IpProtocol.TCP).port(port));
}
 
Example 26
Source Project: brooklyn-server   Source File: SecurityGroupDefinition.java    License: Apache License 2.0 4 votes vote down vote up
public SecurityGroupDefinition allowingInternalPortRange(int portRangeStart, int portRangeEnd) {
    return allowing(IpPermissions.permit(IpProtocol.TCP).fromPort(portRangeStart).to(portRangeEnd));
}
 
Example 27
Source Project: brooklyn-server   Source File: SecurityGroupDefinition.java    License: Apache License 2.0 4 votes vote down vote up
public SecurityGroupDefinition allowingInternalPing() {
    return allowing(IpPermissions.permit(IpProtocol.ICMP));
}
 
Example 28
Source Project: brooklyn-server   Source File: SecurityGroupDefinition.java    License: Apache License 2.0 4 votes vote down vote up
public SecurityGroupDefinition allowingPublicPort(int port) {
    return allowing(IpPermissions.permit(IpProtocol.TCP).port(port).originatingFromCidrBlock(Cidr.UNIVERSAL.toString()));
}
 
Example 29
Source Project: brooklyn-server   Source File: SecurityGroupDefinition.java    License: Apache License 2.0 4 votes vote down vote up
public SecurityGroupDefinition allowingPublicPortRange(int portRangeStart, int portRangeEnd) {
    return allowing(IpPermissions.permit(IpProtocol.TCP).fromPort(portRangeStart).to(portRangeEnd).originatingFromCidrBlock(Cidr.UNIVERSAL.toString()));
}
 
Example 30
Source Project: brooklyn-server   Source File: SecurityGroupDefinition.java    License: Apache License 2.0 4 votes vote down vote up
public SecurityGroupDefinition allowingPublicPing() {
    return allowing(IpPermissions.permit(IpProtocol.ICMP).originatingFromCidrBlock(Cidr.UNIVERSAL.toString()));
}