Example usage for com.amazonaws.util EC2MetadataUtils getNetworkInterfaces

List of usage examples for com.amazonaws.util EC2MetadataUtils getNetworkInterfaces

Introduction

In this page you can find the example usage for com.amazonaws.util EC2MetadataUtils getNetworkInterfaces.

Prototype

public static List<NetworkInterface> getNetworkInterfaces() 

Source Link

Document

Get the list of network interfaces on the instance.

Usage

From source file:com.kixeye.chassis.bootstrap.aws.ServerInstanceContext.java

License:Apache License

private ServerInstanceContext() {
    amazonElasticLoadBalancing = new AmazonElasticLoadBalancingClient();
    amazonEC2 = new AmazonEC2Client();

    ec2MetadataClient = new Ec2MetadataClient() {
        @Override/*  www  . j a v a  2 s . co  m*/
        public String getAvailabilityZone() {
            return EC2MetadataUtils.getAvailabilityZone();
        }

        @Override
        public String getInstanceId() {
            return EC2MetadataUtils.getInstanceId();
        }

        @Override
        public String getUserData() {
            return EC2MetadataUtils.getUserData();
        }

        @Override
        public String getPrivateIpAddress() {
            return EC2MetadataUtils.getPrivateIpAddress();
        }

        @Override
        public String getPublicIpAddress() {
            for (EC2MetadataUtils.NetworkInterface net : EC2MetadataUtils.getNetworkInterfaces()) {
                List<String> ips = net.getPublicIPv4s();
                if (ips != null && ips.size() > 0) {
                    return ips.get(0);
                }
            }
            return null;
        }
    };

    init();
}

From source file:dsmwatcher.DSMWatcher.java

License:Open Source License

public void doRetrieveAgentInformation() throws Exception {
    HostStatusTransport hostStatus;//from   www. j  a  v  a  2  s .c  o  m
    boolean isolationCandidate;
    List<NetworkInterface> netInts = EC2MetadataUtils.getNetworkInterfaces();
    String vpcid = EC2MetadataUtils.getData(
            "/latest/meta-data/network/interfaces/macs/" + netInts.get(0).getMacAddress() + "/vpc-id/");
    String placement = EC2MetadataUtils.getData("/latest/meta-data/placement/availability-zone/");
    region = Regions.fromName(placement.substring(0, placement.length() - 1));
    AmazonEC2Client ec2 = new AmazonEC2Client().withRegion(region);
    DescribeInstancesResult descInstances = ec2.describeInstances(new DescribeInstancesRequest().withFilters(
            new Filter("vpc-id").withValues(vpcid), new Filter("instance-state-name").withValues("running")));
    List<Reservation> runningInstances = descInstances.getReservations();
    _ManagerService = _Service.getManager(new URL(dsmSOAP));
    try {

        _sid = _ManagerService.authenticate(dsmUser, dsmPass);
        HostTransport host;

        RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
        ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor();
        ICloudAccountAPI cloudAPI = ProxyFactory.create(ICloudAccountAPI.class, dsmREST, executor);
        // resync the cloud accounts to ensure the DSM has the latest info
        try {
            CloudAccountListing cloudAccounts = cloudAPI.getCloudAccounts(_sid);
            List<CloudAccountElement> accounts = cloudAccounts.getCloudAccounts();
            for (CloudAccountElement account : accounts)
                if (account.getCloudType().equals("AMAZON"))
                    cloudAPI.synchronizeCloudAccount(account.getCloudAccountId(), _sid);
        } catch (ClientResponseFailure e) {

            ClientResponse<?> clientResponse = e.getResponse();
            javax.ws.rs.core.Response.Status status = clientResponse.getResponseStatus();
            log("Server returned error status code " + status.getStatusCode() + " (" + status + ")");
            ErrorMessage errorMessage = clientResponse.getEntity(ErrorMessage.class);
            log("Returned error message: " + errorMessage.getMessage());
            e.printStackTrace();

        } catch (Exception e) {
            this.log("error:" + e.getMessage());
            e.printStackTrace();

        }
        for (Reservation reservation : runningInstances) {
            List<Instance> instances = reservation.getInstances();
            for (Instance instance : instances) {
                Boolean beenNotified = notifiedInstances.contains(instance.getInstanceId());
                Boolean isExempt = checkExempt(instance, ec2);
                ArrayList<String> violationReasons = new ArrayList<String>();
                host = null;
                isolationCandidate = false;
                if (!instance.getPrivateDnsName().isEmpty())
                    host = _ManagerService.hostRetrieveByName(instance.getPrivateDnsName(), _sid);
                if (host == null)
                    host = _ManagerService.hostRetrieveByName(instance.getInstanceId(), _sid);
                if (host == null && !instance.getPublicDnsName().isEmpty())
                    host = _ManagerService.hostRetrieveByName(instance.getPublicDnsName(), _sid);
                if (host == null && !(instance.getPublicIpAddress() == null))
                    host = _ManagerService.hostRetrieveByName(instance.getPublicIpAddress(), _sid);
                if (host == null)
                    host = _ManagerService.hostRetrieveByName(instance.getPrivateIpAddress(), _sid);
                if (host == null) //giveup
                    error("Error: instance found in DescribeInstances but not found in DSM");
                if (host != null) {
                    hostStatus = (HostStatusTransport) _ManagerService.hostGetStatus(host.getID(), _sid);
                    Boolean isIsolated = checkIfIsolated(instance, ec2);
                    if (hostStatus.getOverallStatus().equals("Unmanaged (Unknown)")) {
                        if (!isIsolated && !isExempt && !beenNotified)
                            log("Found unmanaged instance in EC2:" + instance.getInstanceId()
                                    + " with IP address of " + instance.getPrivateIpAddress()
                                    + " is currently running and not managed by Deep Security.");
                        isolationCandidate = true;
                        violationReasons.add("Instance is unmanaged");

                    } else {

                        // SecurityProfileTransport hostSecurityProfile = _ManagerService.securityProfileRetrieve(hostSecurityProfileID, _sid);
                        if (requireAV && (hostStatus.getOverallAntiMalwareStatus().startsWith(avOn) == false)) {

                            if (!isIsolated && !isExempt && !beenNotified
                                    && (hostStatus.getOverallAntiMalwareStatus().compareTo(
                                            "Anti-Malware: Smart Protection Server Disconnected for Smart Scan") != 0)) {
                                log("Policy violation: Instance " + instance.getInstanceId()
                                        + " with IP address of " + instance.getPrivateIpAddress()
                                        + " found with AV agent disabled");
                                //log("DEBUG: getOverallAntiMalwareStatus() returned:" + hostStatus.getOverallAntiMalwareStatus());
                            }
                            if (!isIsolated && (hostStatus.getOverallAntiMalwareStatus().compareTo(
                                    "Anti-Malware: Smart Protection Server Disconnected for Smart Scan") != 0)) {
                                isolationCandidate = true;
                                violationReasons.add("AV is required but disabled");
                            }
                        }

                        if (requireFW && (hostStatus.getOverallFirewallStatus().substring(0, fwOn.length())
                                .compareTo(fwOn) != 0)) {
                            if (!isIsolated && !isExempt && !beenNotified)
                                log("Policy violation: Instance " + instance.getInstanceId()
                                        + " with IP address of " + instance.getPrivateIpAddress()
                                        + " found with host based firewall disabled");
                            isolationCandidate = true;
                            violationReasons.add("Firewall is required but disabled");
                        }

                        if (requireFIM && (hostStatus.getOverallIntegrityMonitoringStatus()
                                .substring(0, fimOn.length()).compareTo(fimOn) != 0)) {
                            if (!isIsolated && !isExempt && !beenNotified)
                                log("Policy violation: Instance " + instance.getInstanceId()
                                        + " with IP address of " + instance.getPrivateIpAddress()
                                        + " found with file integrity monitoring disabled");
                            isolationCandidate = true;
                            violationReasons.add("File Integrity Monitoring is required but disabled");
                        }

                        if (requireDPI && (hostStatus.getOverallDpiStatus().substring(0, dpiOn.length())
                                .compareTo(dpiOn) != 0)) {
                            if (!isIsolated && !isExempt && !beenNotified)
                                log("Policy violation: Instance " + instance.getInstanceId()
                                        + " with IP address of " + instance.getPrivateIpAddress()
                                        + " found with deep packet inspection disabled or in an invalid mode");
                            isolationCandidate = true;
                            violationReasons.add(
                                    "Deep Packet Instection is required but disabled or not in enforce mode");
                        }

                    }

                    if (isolationCandidate && enableIsolation && !isIsolated && !isExempt) {
                        log("Instance " + instance.getInstanceId()
                                + " will be isolated for failing one or more policy checks");
                        notifyAdmin(instance, violationReasons, false);
                        notifiedInstances.add(instance.getInstanceId());
                        isolateInstance(instance, ec2);

                    }
                    if (isolationCandidate && !enableIsolation && !isIsolated && !isExempt && !beenNotified) {
                        log("Instance " + instance.getInstanceId()
                                + " is elligable for isolation but enforcement is disabled");
                        notifyAdmin(instance, violationReasons, false);
                        notifiedInstances.add(instance.getInstanceId());
                    }

                    if (!isolationCandidate && isIsolated) {
                        removeIsolation(instance, ec2);
                        notifyAdmin(instance, violationReasons, true);
                    }
                    if (beenNotified && !isolationCandidate)
                        notifiedInstances.remove(instance.getInstanceId());
                }

            }
        }
    }

    catch (Exception e) {
        this.log("Error: " + e.getMessage());
        e.printStackTrace();
    }
    if (_sid != null)
        _ManagerService.endSession(_sid);

}

From source file:dsmwatcher.DSMWatcher.java

License:Open Source License

public Boolean checkExempt(Instance instance, AmazonEC2Client ec2) throws Exception {
    //check for DSM IP address, address of ourself, presence of the EXEMPTTAG
    // and if Start Time is < 5 mintues from now
    List<Tag> tagSet = instance.getTags();
    //EC2MetadataUtils metadata = new EC2MetadataUtils();
    List<NetworkInterface> netInts = EC2MetadataUtils.getNetworkInterfaces();
    String myIP = netInts.get(0).getLocalIPv4s().get(0);
    if (instance.getPrivateIpAddress().compareTo(myIP) == 0) {
        return true;
    }//from  w  w  w  . j av  a 2  s.  co m
    if (instance.getPrivateIpAddress().compareTo(dsmIP) == 0) {
        return true;
    }
    for (Tag tag : tagSet) {
        if ((tag.getKey().compareTo(exemptTag) == 0) && (tag.getValue().compareTo(exemptTagValue)) == 0) {
            return true;
        }
    }
    if ((instance.getLaunchTime().getTime() + 300000) > System.currentTimeMillis()) {
        return true;
    }
    return false;
}

From source file:gobblin.aws.GobblinAWSTaskRunner.java

License:Apache License

private static String getTaskRunnerId() {
    return EC2MetadataUtils.getNetworkInterfaces().get(0).getPublicIPv4s().get(0);
}