List of usage examples for com.amazonaws.services.ec2 AmazonEC2Client describeSecurityGroups
@Override
public DescribeSecurityGroupsResult describeSecurityGroups()
From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.util.AwsDataSourceRecovery.java
License:Open Source License
private String recoverVpcSecurityGroup(AwsReportDataSource awsReportDataSource, String vpcId, String ingressPublicIp) { AWSCredentials awsCredentials = AwsCredentialUtil.getAWSCredentials(awsReportDataSource.getAWSAccessKey(), awsReportDataSource.getAWSSecretKey(), awsReportDataSource.getRoleARN()); //Security//from ww w . ja va 2 s .c o m AmazonEC2Client amazonEc2Client = new AmazonEC2Client(awsCredentials); SecurityGroup vpcSecurityGroup = null; try { DescribeSecurityGroupsResult describeSecurityGroupsResult = amazonEc2Client.describeSecurityGroups(); if (describeSecurityGroupsResult != null && describeSecurityGroupsResult.getSecurityGroups() != null && describeSecurityGroupsResult.getSecurityGroups().size() > 0) { for (SecurityGroup securityGroup : describeSecurityGroupsResult.getSecurityGroups()) { if (securityGroup.getVpcId() != null && securityGroup.getVpcId().equals(vpcId) && securityGroup.getGroupName().equals(awsProperties.getSecurityGroupName())) { vpcSecurityGroup = securityGroup; break; } } } } catch (Exception ex) { //Have to be empty. } boolean ingressIpMaskExist = false; String vpcSecurityGroupId; if (vpcSecurityGroup != null) { vpcSecurityGroupId = vpcSecurityGroup.getGroupId(); List<IpPermission> ipPermissions = vpcSecurityGroup.getIpPermissions(); if (ipPermissions != null && ipPermissions.size() > 0) { for (IpPermission ipPermission : ipPermissions) { if (ipPermission.getIpRanges() != null && ipPermission.getIpRanges().size() > 0 && ipPermission.getIpRanges().contains(ingressPublicIp)) { ingressIpMaskExist = true; } } } if (!ingressIpMaskExist && ipPermissions != null && ipPermissions.size() > 0) { RevokeSecurityGroupIngressRequest revokeSecurityGroupIngressRequest = new RevokeSecurityGroupIngressRequest() .withGroupId(vpcSecurityGroup.getGroupId()).withIpPermissions() .withIpPermissions(vpcSecurityGroup.getIpPermissions()); amazonEc2Client.revokeSecurityGroupIngress(revokeSecurityGroupIngressRequest); } } else { vpcSecurityGroupId = amazonEc2Client .createSecurityGroup( new CreateSecurityGroupRequest().withGroupName(awsProperties.getSecurityGroupName()) .withVpcId(vpcId).withDescription(awsProperties.getSecurityGroupDescription())) .getGroupId(); } if (!ingressIpMaskExist) { IpPermission ipPermission = new IpPermission().withIpProtocol("tcp").withIpRanges(ingressPublicIp) .withFromPort(0).withToPort(65535); List<IpPermission> ipPermissions = new ArrayList<IpPermission>(); ipPermissions.add(ipPermission); AuthorizeSecurityGroupIngressRequest authorizeRequest = new AuthorizeSecurityGroupIngressRequest() .withIpPermissions(ipPermissions).withGroupId(vpcSecurityGroupId); amazonEc2Client.authorizeSecurityGroupIngress(authorizeRequest); } return vpcSecurityGroupId; }
From source file:io.macgyver.plugin.cloud.aws.scanner.SecurityGroupScanner.java
License:Apache License
@Override public void scan(Region region) { AmazonEC2Client client = getAWSServiceClient().createEC2Client(region.getName()); DescribeSecurityGroupsResult result = client.describeSecurityGroups(); long now = System.currentTimeMillis(); GraphNodeGarbageCollector gc = newGarbageCollector().region(region).label("AwsSecurityGroup"); result.getSecurityGroups().forEach(sg -> { ObjectNode g = convertAwsObject(sg, region); // non-VPC security groups don't have a VPC String vpcId = Strings.nullToEmpty(sg.getVpcId()); String cypher = "merge (sg:AwsSecurityGroup {aws_account: {a}, aws_region: {r}, aws_vpcId: {vpcId}, aws_groupId: {groupId}}) set sg+={props}, sg.updateTs={now} return sg"; JsonNode xx = getNeoRxClient().execCypher(cypher, "vpcId", vpcId, "groupId", sg.getGroupId(), "props", g, "now", now, "a", getAccountId(), "r", region.getName()).toBlocking().first(); gc.updateEarliestTimestamp(xx);/*w w w.j a va2 s . c o m*/ if (!vpcId.isEmpty()) { cypher = "match (v:AwsVpc {aws_vpcId: {vpcId}}), (sg:AwsSecurityGroup {aws_groupId:{groupId}, aws_vpcId: {vpcId}}) merge (sg)-[:RESIDES_IN]->(v)"; getNeoRxClient().execCypher(cypher, "vpcId", vpcId, "groupId", sg.getGroupId()); } }); gc.invoke(); }
From source file:n3phele.factory.ec2.VirtualServerResource.java
License:Open Source License
private boolean makeSecurityGroup(String groupName, String id, String secret, URI location, String to, String firstName, String lastName) { AmazonEC2Client client = null; client = getEC2Client(id, secret, location); boolean found = true; boolean failed = false; try {// w w w. jav a 2 s. c o m client.createSecurityGroup(new CreateSecurityGroupRequest().withGroupName("n3phele-" + groupName) .withDescription("n3phele " + groupName + " security group")); String ownerId = null; DescribeSecurityGroupsResult newGroupResult = client.describeSecurityGroups(); for (SecurityGroup g : newGroupResult.getSecurityGroups()) { if (g.getGroupName().equals("n3phele-" + groupName)) { ownerId = g.getOwnerId(); } } if (ownerId == null) return false; log.info("found ownerId of " + ownerId); log.info("adding ssh ports"); try { client.authorizeSecurityGroupIngress( new AuthorizeSecurityGroupIngressRequest().withGroupName("n3phele-" + groupName) .withCidrIp("0.0.0.0/0").withIpProtocol("tcp").withFromPort(22).withToPort(22)); } catch (Exception e) { log.log(Level.SEVERE, "Create security group " + groupName, e); failed = true; } log.info("adding agent ports"); try { client.authorizeSecurityGroupIngress( new AuthorizeSecurityGroupIngressRequest().withGroupName("n3phele-" + groupName) .withCidrIp("0.0.0.0/0").withIpProtocol("tcp").withFromPort(8887).withToPort(8887)); } catch (Exception e) { log.log(Level.SEVERE, "Create security group " + groupName, e); failed = true; } if (!failed) { log.info("adding self access"); try { List<IpPermission> permissions = new ArrayList<IpPermission>(); UserIdGroupPair userIdGroupPairs = new UserIdGroupPair().withUserId(ownerId) .withGroupName("n3phele-" + groupName); permissions.add(new IpPermission().withIpProtocol("icmp").withFromPort(-1).withToPort(-1) .withUserIdGroupPairs(userIdGroupPairs)); permissions.add(new IpPermission().withIpProtocol("tcp").withFromPort(1).withToPort(65535) .withUserIdGroupPairs(userIdGroupPairs)); permissions.add(new IpPermission().withIpProtocol("udp").withFromPort(1).withToPort(65535) .withUserIdGroupPairs(userIdGroupPairs)); log.info("adding icmp/tcp/udp"); client.authorizeSecurityGroupIngress( new AuthorizeSecurityGroupIngressRequest("n3phele-" + groupName, permissions)); } catch (Exception e) { log.log(Level.WARNING, "Error adding self access to group " + groupName, e); } } if (failed) { client.deleteSecurityGroup(new DeleteSecurityGroupRequest().withGroupName("n3phele-" + groupName)); found = false; } else { sendSecurityGroupNotificationEmail("n3phele-" + groupName, to, firstName, lastName, location); } } catch (Exception e) { log.log(Level.SEVERE, "Create security group " + groupName, e); client.deleteSecurityGroup(new DeleteSecurityGroupRequest().withGroupName("n3phele-" + groupName)); found = false; } return found; }
From source file:org.elasticdroid.model.EC2DashboardModel.java
License:Open Source License
/** * Gets the data to populate the EC2 Dashboard with in the background thread, and loads it into * a Hashtable<String, Integer>. /*from ww w. j a v a 2 s . c om*/ * * @param This method accepts *ONE* Hashtable<String, String> of LoginDetails arguments. The * required keys are as follows (anything else is ignored): * <ul> * <li> accessKey: The accesskey for the AWS/AWS IAM account used.</li> * <li> secretAccessKey: The secretAccessKey for the AWS/AWS IAM account used.</li> * <li> endpoint: AWS Endpoint for the selected region (@see {@link AWSConstants.EndPoints}</li> * </ul> * If you're missing any of these keys, AmazonServiceExceptions will be thrown. This shouldn't * be visible to the end-user as this is a programmer fault!!! :P * * @return This method can return: * <ul> * <li>{@link IllegalArgumentException}: If there are too many/few arguments, or the keys are * incorrect. Only one Hashtable<String, String> accepted.</li> * <li>{@link Hashtable<String, Integer}: data to populate dashboard with. * <ul> * <li><i>runningInstances:</i> The number of running instances for the user in the current * region</li> * <li><i>stoppedInstances:</i> The number of stopped instances for the user in the current * region</li> * <li><i>elasticIp:</i> The number of elastic IPs owned by the user (in the current region) * </li> * <li><i>securityGroups:</i> The number of security groups avail 2 the user (in the current * region)</li> * <li><i>keyPairs:</i> The number of keypairs avail 2 the user (in the current * region)</li> * </ul> * </li> * </ul> */ @SuppressWarnings("unchecked") @Override protected Object doInBackground(HashMap<?, ?>... params) { HashMap<String, String> connectionData; HashMap<String, Integer> dashboardData; //we accept only one param, but AsyncTask forces us to potentially accept //a whole bloody lot of them. :P if (params.length != 1) { return new IllegalArgumentException( "Only one Hashtable<String,String> parameter " + "should be passed."); } connectionData = (HashMap<String, String>) params[0]; //convenience variable, so that //i dont have to keep typing params[0] everywhere in this method.;) Log.v(this.getClass().getName(), "Getting EC2 dashboard data..."); //prepare to get the dashboard data! //create credentials using the BasicAWSCredentials class BasicAWSCredentials credentials = new BasicAWSCredentials(connectionData.get("accessKey"), connectionData.get("secretAccessKey")); //create Amazon EC2 Client object, and set tye end point to the region. params[3] //contains endpoint AmazonEC2Client amazonEC2Client = new AmazonEC2Client(credentials); amazonEC2Client.setEndpoint(connectionData.get("endpoint")); //initialise result holder variable dashboardData = new HashMap<String, Integer>(); try { //get the number of running and stopped instances DescribeInstancesResult instances = amazonEC2Client.describeInstances(); int numOfRunningInstances = 0; int numOfStoppedInstances = 0; //get the list of reservations in the results for (Reservation reservation : instances.getReservations()) { //for each reservation, get the list of instances associated for (Instance instance : reservation.getInstances()) { if (instance.getState().getCode().byteValue() == InstanceStateConstants.RUNNING) { numOfRunningInstances++; } else if (instance.getState().getCode().byteValue() == InstanceStateConstants.STOPPED) { numOfStoppedInstances++; } } } dashboardData.put("runningInstances", numOfRunningInstances); dashboardData.put("stoppedInstances", numOfStoppedInstances); //get the list of elastic Ips. dashboardData.put("elasticIp", amazonEC2Client.describeAddresses().getAddresses().size()); //get the list of security groups dashboardData.put("securityGroups", amazonEC2Client.describeSecurityGroups().getSecurityGroups().size()); //get the list of keypairs dashboardData.put("keyPairs", amazonEC2Client.describeKeyPairs().getKeyPairs().size()); } catch (AmazonServiceException amazonServiceException) { return amazonServiceException; } catch (AmazonClientException amazonClientException) { return amazonClientException; } return dashboardData; }