Example usage for com.amazonaws.util EC2MetadataUtils getData

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

Introduction

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

Prototype

public static String getData(String path) 

Source Link

Usage

From source file:dsmwatcher.DSMWatcher.java

License:Open Source License

public void doRetrieveAgentInformation() throws Exception {
    HostStatusTransport hostStatus;// w  w  w . ja v a2  s  .c om
    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:org.springframework.cloud.aws.core.env.ec2.AmazonEc2InstanceDataPropertySource.java

License:Apache License

@Override
public Object getProperty(String name) {
    Map<String, String> userData = getUserData();
    if (userData.containsKey(name)) {
        return userData.get(name);
    }//from w  ww  .ja  va 2 s  .  c o m

    if (!KNOWN_PROPERTY_NAMES.containsKey(getRootPropertyName(name))) {
        return null;
    }

    try {
        return EC2MetadataUtils.getData(EC2_METADATA_ROOT + "/" + name);
    } catch (AmazonClientException e) {
        //Suppress exception if we are not able to contact the service,
        //because that is quite often the case if we run in unit tests outside the environment.
        LOGGER.warn("Error getting instance meta-data with name '{}' error message is '{}'", name,
                e.getMessage());
        return null;
    }
}