org.jclouds.net.domain.IpProtocol Java Examples

The following examples show how to use org.jclouds.net.domain.IpProtocol. 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: NovaLauncherTest.java    From karamel with 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 File: DescribeSecurityGroupsResponseTest.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: AWSSecurityGroupApiTest.java    From attic-stratos with 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 #4
Source File: AWSSecurityGroupApiTest.java    From attic-stratos with 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 #5
Source File: NetworkingEffectors.java    From brooklyn-server with 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 #6
Source File: JcloudsRateLimitedRetryLiveTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private IpPermission aPermission() {
    return IpPermission.builder()
        .ipProtocol(IpProtocol.TCP)
        .fromPort(22)
        .toPort(22)
        .cidrBlock("0.0.0.0/0")
        .build();
}
 
Example #7
Source File: AWSEC2IpPermissionHandler.java    From attic-stratos with 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 #8
Source File: AWSEC2SecurityGroupExtension.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@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 #9
Source File: AWSEC2SecurityGroupExtension.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@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 #10
Source File: NetworkingEffectorsLiveTests.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
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 #11
Source File: SharedLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
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 #12
Source File: SharedLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@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 #13
Source File: SharedLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@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 #14
Source File: SharedLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@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 #15
Source File: SharedLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@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 #16
Source File: JcloudsLocationSecurityGroupCustomizerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private IpPermission newPermission(int port) {
    return IpPermission.builder()
            .ipProtocol(IpProtocol.TCP)
            .fromPort(port)
            .toPort(port)
            .cidrBlock("0.0.0.0/0")
            .build();
}
 
Example #17
Source File: SharedLocationSecurityGroupCustomizer.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
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 #18
Source File: SharedLocationSecurityGroupCustomizer.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
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 #19
Source File: SharedLocationSecurityGroupCustomizer.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
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 #20
Source File: RiakNodeImpl.java    From brooklyn-library with 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 #21
Source File: NovaLauncherTest.java    From karamel with 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 #22
Source File: AWSSecurityGroupApiLiveTest.java    From attic-stratos with 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 #23
Source File: JcloudsLocationSecurityGroupCustomizer.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #24
Source File: Ec2Launcher.java    From karamel with 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 File: AWSEC2CreateSecurityGroupIfNeededTest.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testWhenPort22AndToItselfAuthorizesIngressOnce() throws ExecutionException {

   AWSSecurityGroupApi client = createMock(AWSSecurityGroupApi.class);
   Predicate<RegionAndName> tester = Predicates.alwaysTrue();

   SecurityGroup group = createNiceMock(SecurityGroup.class);
   Set<SecurityGroup> groups = ImmutableSet.<SecurityGroup> of(group);

   EC2SecurityGroupIdFromName groupIdFromName = createMock(EC2SecurityGroupIdFromName.class);

   ImmutableSet.Builder<IpPermission> permissions = ImmutableSet.builder();

   permissions.add(IpPermission.builder()
                   .fromPort(22)
                   .toPort(22)
                   .ipProtocol(IpProtocol.TCP)
                   .cidrBlock("0.0.0.0/0")
                   .build());

   permissions.add(IpPermission.builder()
                   .fromPort(0)
                   .toPort(65535)
                   .ipProtocol(IpProtocol.TCP)
                   .tenantIdGroupNamePair("ownerId", "sg-123456")
                   .build());
   permissions.add(IpPermission.builder()
                   .fromPort(0)
                   .toPort(65535)
                   .ipProtocol(IpProtocol.UDP)
                   .tenantIdGroupNamePair("ownerId", "sg-123456")
                   .build());
   
   client.createSecurityGroupInRegion("region", "group", "group");
   expect(group.getOwnerId()).andReturn("ownerId");
   expect(groupIdFromName.apply("region/group")).andReturn("sg-123456");
   client.authorizeSecurityGroupIngressInRegion("region", "sg-123456", permissions.build());
   expect(client.describeSecurityGroupsInRegion("region", "group")).andReturn(Set.class.cast(groups));


   replay(client);
   replay(group);
   replay(groupIdFromName);

   AWSEC2CreateSecurityGroupIfNeeded function = new AWSEC2CreateSecurityGroupIfNeeded(client, groupIdFromName, tester);

   assertEquals("group", function.load(new RegionNameAndIngressRules("region", "group", new int[] { 22 }, true)));

   verify(client);
   verify(group);
   verify(groupIdFromName);

}
 
Example #26
Source File: AWSSecurityGroupApiLiveTest.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
@Test
void testAuthorizeSecurityGroupIngressIpPermission() throws InterruptedException {
   final String group1Name = PREFIX + "ingress11";
   String group2Name = PREFIX + "ingress12";
   cleanupAndSleep(group2Name);
   cleanupAndSleep(group1Name);
   try {
      final String group1Id = AWSSecurityGroupApi.class.cast(client).createSecurityGroupInRegionAndReturnId(null,
            group1Name, group1Name);
      final String group2Id = AWSSecurityGroupApi.class.cast(client).createSecurityGroupInRegionAndReturnId(null,
            group2Name, group2Name);
      Thread.sleep(100);  // eventual consistent
      ensureGroupsExist(group1Name, group2Name);
      AWSSecurityGroupApi.class.cast(client).authorizeSecurityGroupIngressInRegion(null, group1Id,
            IpPermissions.permit(IpProtocol.TCP).port(80));
      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);
      IpPermissions group2CanHttpGroup1 = IpPermissions.permit(IpProtocol.TCP).port(80)
            .originatingFromSecurityGroupId(group1Id);
      AWSSecurityGroupApi.class.cast(client).authorizeSecurityGroupIngressInRegion(null, group2Id,
            group2CanHttpGroup1);
      assertEventually(new GroupHasPermission(client, group2Name, new Predicate<IpPermission>() {
         @Override
         public boolean apply(IpPermission arg0) {
            return arg0.getTenantIdGroupNamePairs().equals(ImmutableMultimap.of(group.getOwnerId(), group1Id))
                  && arg0.getFromPort() == 80 && arg0.getToPort() == 80 && arg0.getIpProtocol() == IpProtocol.TCP;
         }
      }));

      AWSSecurityGroupApi.class.cast(client).revokeSecurityGroupIngressInRegion(null, group2Id,
            group2CanHttpGroup1);
      assertEventually(new GroupHasNoPermissions(client, group2Name));
   } finally {
      client.deleteSecurityGroupInRegion(null, group2Name);
      client.deleteSecurityGroupInRegion(null, group1Name);
   }
}
 
Example #27
Source File: AWSEC2CreateSecurityGroupIfNeeded.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
private void createSecurityGroupInRegion(String region, String name, int... ports) {
   checkNotNull(region, "region");
   checkNotNull(name, "name");
   logger.debug(">> creating securityGroup region(%s) name(%s)", region, name);

   try {
      securityApi.createSecurityGroupInRegion(region, name, name);
      boolean created = securityGroupEventualConsistencyDelay.apply(new RegionAndName(region, name));
      if (!created)
         throw new RuntimeException(String.format("security group %s/%s is not available after creating", region,
               name));
      logger.debug("<< created securityGroup(%s)", name);

      ImmutableSet.Builder<IpPermission> permissions = ImmutableSet.builder();
      String id;
      if (name.startsWith("sg-")) {
         id = name;
      } else {
         id = groupNameToId.apply(new RegionAndName(region, name).slashEncode());
      }

      if (ports.length > 0) {
         for (Map.Entry<Integer, Integer> range : getPortRangesFromList(ports).entrySet()) {
            permissions.add(IpPermission.builder()
                            .fromPort(range.getKey())
                            .toPort(range.getValue())
                            .ipProtocol(IpProtocol.TCP)
                            .cidrBlock("0.0.0.0/0")
                            .build());
         }

         String myOwnerId = Iterables.get(securityApi.describeSecurityGroupsInRegion(region, name), 0).getOwnerId();
         permissions.add(IpPermission.builder()
                         .fromPort(0)
                         .toPort(65535)
                         .ipProtocol(IpProtocol.TCP)
                         .tenantIdGroupNamePair(myOwnerId, id)
                         .build());
         permissions.add(IpPermission.builder()
                         .fromPort(0)
                         .toPort(65535)
                         .ipProtocol(IpProtocol.UDP)
                         .tenantIdGroupNamePair(myOwnerId, id)
                         .build());
      }

      Set<IpPermission> perms = permissions.build();

      if (!perms.isEmpty()) {
         logger.debug(">> authorizing securityGroup region(%s) name(%s) IpPermissions(%s)", region, name, perms);
         securityApi.authorizeSecurityGroupIngressInRegion(region, id, perms);
         logger.debug("<< authorized securityGroup(%s)", name);
      }

   } catch (IllegalStateException e) {
      logger.debug("<< reused securityGroup(%s)", name);
   }
}
 
Example #28
Source File: SecurityGroupDefinition.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public SecurityGroupDefinition allowingPublicPing() {
    return allowing(IpPermissions.permit(IpProtocol.ICMP).originatingFromCidrBlock(Cidr.UNIVERSAL.toString()));
}
 
Example #29
Source File: SecurityGroupDefinition.java    From brooklyn-server with 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 File: SecurityGroupDefinition.java    From brooklyn-server with 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()));
}