Amazon aws Public IP from running Instance using Java - java

I made a Java program which allows to create instances Programatically.
I need to parse the return object to print the public IP address of the Instance.
However when I output the result of the describeInstances() function of Amazon's EC2 client, the output is a maze of lists and hash maps and I don't know how to parse it.
Can anybody tell me a more simpler approach to accomplish this?
I tried to convert the Ec2.describeInstances().getReservations() result to a string and then manipulate the string to output the Public IP address.
Is there any simpler way to accomplish this?
Code:
DescribeAddressesRequest add =new DescribeAddressesRequest();
String Desc= client.describeInstances().getReservations().get(1).toString();

The SDK doesn't return HashMaps it returns actual Java classes. I'm not sure how you are getting HashMaps out of it. Converting the returned object to a String and manipulating that is definitely not the recommended approach.
If you look at the API docs you will see that describeInstances() returns a DescribeInstancesResult which contains a list of Reservation objects, which each contain a list of Instance objects. The Instance object has a getPublicIpAddress() method. So you could do something like the following:
DescribeInstancesRequest request = new DescribeInstancesRequest();
String ipAddress = client.describeInstances(request) // You pass the request here
.getReservations().get(0) // Get the first reservation
.getInstances().get(0) // Get the first instance in the reservation
.getPublicIpAddress(); // Get the public IP address of the instance
I assume you're adding some criteria, like the reservation ID, to the DescribeInstancesRequest object so that you can expect only one instance to be in the response.
Note that the public IP address might not be assigned immediately. You may have to do this in a loop, checking if the IP address has been assigned yet.

You need an Instance class
getPublicIpAddress()
The public IPv4 address assigned to the instance, if applicable
I don't know the API, but from a Reservation, you get to an Instance.
getInstances()
One or more instances
for (Reservation r : client.describeInstances().getReservations()) {
for (Instance i : r.getInstances()) {
String ipv4 = i.getPublicIpAddress();
}
}

Related

Java - How can I completely clear a variable

I have a Spring Boot application that uses a CredentialsService class to store credentials as GuardedStrings and return them when requested by other classes.
Where the problem arises is in the fact that we use Checkmarx to scan our code and catch potential issues. Where storage of the usernames/passwords are not a problem anymore, I still have to use a String variable to return the plain text credentials. Checkmarx doesn't like that - especially for passwords.
This is the abbreviated view of the CredentialsService:
#Component
public class CredentialsService {
final ExecutorService executor = Executors.newSingleThreadExecutor();
private GuardedString customerApiPassword;
. . .
private StringBuilder clearCustomerApiPassword;
public CredentialsService( . . .
#Value("${customerapi.pwd}") String customerApiPassword,. . .) {
setCustomerApiPassword(customerApiPassword);
. . .
}
private void setCustomerApiPassword(String customerApiPasswordString) {
this.customerApiPassword = new GuardedString(customerApiPasswordString.toCharArray());
this.customerApiPassword.makeReadOnly();
}
public String getCustomerApiPasswordNo() {
clearCustomerApiPassword = new StringBuilder();
customerApiPassword.access(new GuardedString.Accessor() {
#Override
public void access(final char[] clearChars) {
clearCustomerApiPassword.append(clearChars);
}
});
customerApiPassword.dispose();
System.out.println("DGC: clearCustomerApiPassword is " + clearCustomerApiPassword);
Runnable clearFromMemory = () -> {
clearCustomerApiPassword = null;
System.out.println("DGC: clearCustomerApiPassword is " + clearCustomerApiPassword);
};
executor.execute(clearFromMemory);
return clearCustomerApiPassword.toString();
}
And then a requester accesses the values it needs with:
IntegrationApiUtil.setBasicAuthKey(headers, credentialsService.getCustomerApiUsername(), credentialsService.getCustomerApiPassword());
However Checkmarx is still not happy. I use the same approach for storing the GuardedString usernames and passwords and the exact same approach to clearing the Strings that are returned. Checkmarx is fine with the usernames, but it still complains about the passwords:
Method clearCustomerApiPassword; at line 24 of
src/main/java/com/.../service/CredentialsService.java
defines clearCustomerApiPassword, which is designated to contain user passwords. However, while plaintext
passwords are later assigned to clearCustomerApiPassword, this variable is never cleared from memory.
I have tried all sorts of things - a finalize method to destroy the service after it is last used, a disposeAll method to explicitly set all variables to null and call the garbage collector. With the code above I am creating a separate thread in each get method to set the 'clear' variables to null as I return the value to the requester. While I can confirm that this latest approach does provide the requester with the correct values and also sets the variables to null, nothing seems to satisfy Checkmarx.
Does anyone have any ideas?
Thanks in advance.
D
Once you put sensitive data into an immutable object like String, the data will remain in the memory for a long time. You can release the variable, but even without a physical reference the value will still sit in the memory. You can run GC, it will still be there. The only thing that would help would be a creation of another variable using the same memory space and overriding the value.
Long story short: As long as you put your password in a String, Checkmarx will complain.
You have two things you can do:
you either rely on char[] only and clear the array once used,
or use a String value if you are forced to and request a special exception for your case.
Well, you are kinda throwing away all the value of storing passwords in GuardedString by returning/transporting them as regular String.
Don't know a lot about Checkmarx, but it's just a code scanning tool, so it's easy to fool. I suggest actually fixing the problems, instead of trying to sweep them under the rug.
Notice that GuardedString constructor accepts char[], not a String. That's the first problem - you should carry your password from the source up to this point as a char[] - more about it here.
Don't return String to your consumer - return the GuardedString or at least a char[].
Depends on what consumers you are targeting with this class/library, but try to provide a way for them to access the actual passwords for as short time as possible, and clearning the char[] after usage (in a way that consumer will not have to do that himself, since he can forget)

Error reading objects from Gemalto smartcard using IAIK pkcs11wrapper

I'm trying to read the public certificate names from a smartcard to display to the user before they sign a file using a gemalto smartcard.
I've followed the getInfo example from iaikPkcs11Wrapper demos as below :
Module pkcs11Module = Module.getInstance(settings.getCryptoDll());
Slot[] slotList;
try{
slotList = pkcs11Module.getSlotList(true);
}catch(TokenException tex){//module is not initialised
tex.printStackTrace();
pkcs11Module.initialize(new DefaultInitializeArgs());
slotList = pkcs11Module.getSlotList(true);
}
for (Slot slot : slotList) {
Token token = slot.getToken();
iaik.pkcs.pkcs11.Session session = token.openSession(true, SessionReadWriteBehavior.RO_SESSION, null, null);
session.findObjectsInit(null);
Object[] objects = new Object[0];
try {
objects = session.findObjects(1);
This fails always at the line objects = findObjects(1); with a CKR_TEMPLATE_INCONSISTENT exception.
As I understand from the documentation session.findObjectsInit(null) should just return all accessible objects on the card and you can then compare them for type.
I have various smartcards and they all fail like this, I've also tried calling session.findObjectsInit(tempObj) with a GenericTemplate object and a X509PublicKeyCertificate which both return the same exception, and with an X509AttributeCertificate which returns no objects but does not throw the exception.
I'd appreciate any pointers anyone can give. Or do I need to create a matching template object using GenericTemplate? I'm unsure why I'm getting the exception as I thought passing the object into the getObjectInit method filtered for thet object so anything returned should match.
EDIT
I've subsequently tried with other templates and ones for objects not on the card just return an empty array- no exception and ones I think are on the cards just throw the ckr_template_inconsistent exception, any help would be gratefully received.
EDIT2
I've now tried with some new 'V3' cards, which do infact work, all my test cards work using another technique (we currently use capicom via com4J for signing), so maybe there is an issue with the iaik wrapper, or gclib.dll (or me).

Java Code to fetch Session Store attribute values

I am writing an Assertion Generator Plugin in Java to fetch a user details from Session Store and modify the values in Assertion(SAML 2.0) accordingly.
I am able to identify the method(Link) using which I can pull the user values from Session Store (agentAPIObject.getSessionVariables()) based on SessionID, but, I am having trouble writing a code to fetch specific parameters from the session store. (speficially around setting values for Attribute method and making it as an array)
Can someone post a sample code if you have ever seen/written around it, so that I can fetch user attributes from Session Store.
I am having trouble understanding Java docs around it.
Thanks in advance,
The API mentions this:
responseAttributeList - On successful return from this method (YES is
returned), this output parameter contains the retrieved variable names
and their values. If the method returns UNRESOLVED, this parameter
includes variables that could not be retrieved.
You'll need to create two AttributeList Objects. If the response of getSessionVariables(...) is YES, then the variable responseAttributeList will contain the session variables. Since Java uses references, that same variable responseAttributeList will be updated. You can then use getAttributeAt(...) to access the Attribute Objects.
String sessionID = "sampleID";
ResourceContextDef rcd = //whatever it needs to be equal to
AttributeList requestAttributeList = new AttributeList();
AttributeList responseAttributeList = new AttributeList();
if(getSessionVariables(sessionId, rcd, requestAttributeList, responseAttributeList) == YES){
Attribute att = responseAttributeList.getAttributeAt(0);//or whatever index.
}
Remember to carefully read the API.
NOTE: This is just pseudo code. I have not tested this. However, this should be plenty enough to get you going where you need to.

how to access the variable in the object passed from client?

First of all I am new to Java programming and object oriented style programming. I started learning it on January this year.
Basically i have a class name vehicleInformation with some local variable.
Then I i prompt the information in the client side and then store it in a object vehicleInformation. Then pass the object to the server side. My instruction is to insert the data in the object to the database. My question is how do i access to the data in the object when it is pass from the client side.
the code below show how i create the object and send it to the server.
vehicleInformation v = new vehicleInformation(plateNumber,vehicleType, engineNumber, chassisNumber, make, model);
toServer.writeObject(v);
the code below is how i read the object but I have no idea how to access to the variable in the obect as we normally use objectName.variable to access it.
Object object = inputFromClient.readObject();
To be safe you should check the type of the object before the typecast.
if (object instanceof VehicleInformation) {
vehicleInformation = (VehicleInformation) object;
}
else {
// Do something with the unexpected object type. e.g. throw an exception.
...
}
You can typecast
VehicleInformation vehicleObject = (VehicleInformation)inputFromClient.readObject();
Cast your object to vehicleInformation.
vehicleInformation objectname = (vehicleInformation)inputFromClient.readObject();
and get variable objectname.variable
And follow class naming convention for better visibility.

Java DataStructure for writing 4 pieces of information

I need to extract two pieces of information about two IP addresses and then write those information plus two addresses.
I was thinking of a Set of Pairs for IP addresses, but by which data structure I can write all these information?
Thanks
PcapPacketHandler<String> jPacketHandler = new PcapPacketHandler<String>(){
int totalLength = 0;
public void nextPacket(PcapPacket packet, String user) {
Ip4 ip = new Ip4();
String sIP;
String dIP;
if (packet.hasHeader(ip) == false){
return;
}
totalLength = totalLength+ ip.getPayloadLength();
sIP = org.jnetpcap.packet.format.FormatUtils.ip(ip.source());
dIP = org.jnetpcap.packet.format.FormatUtils.ip(ip.destination());
System.out.println("SIP = "+sIP+" "+"destIP = "+dIP+" "+"Payload Length = "+ip.getPayloadLength());
System.out.println("Total Length = "+totalLength);
}
};
pcap.loop(10, jPacketHandler, "");
pcap.close();
Even though this isn't a Javascript app, you could use JSON as it provides a concise way to read/store multiple pieces of data together. Check out the JSON Java Documentation for details about classes, and to download the related source.
If you're just writing the information you could always use a Hashmap. Unless you know what you're planning to do with the data, it's hard to say what's best.
Just make a custom class (POJO), and depending on how you want to write it make it Serializable. That way you can clearly name your fields (and getters and setters) making your code easier to read (and extend).
some thing like this...
class BigClass { //<br>
private IPAdreess addr1; //<br>
private IPAddress addr2; //<br>
private SomeInfo additionalInfo;//<br>
//implement accessors//<br>
//implement equals, hashCode//<br>
}//<br>
IPAddress, SomeInfo are your user types. In java, InetAddress represents IP address. This may be much more than your custom type.
The selection of suitable data structure of "set" could be decided many factors.. Do you want to retain the order? Do you populate it via multiple threads? How many entries you expect in the set? 100s? A million?
Why not post your code? It may be easier to give feedback with real code..
I don't quite understand what graph you exactly want to plot. What I would do is
Dump all data into an sql database
Run a query to produce input for your chart.
Plot the chart e.g. with JFreeChart or even Excel
I imagine a query along the line
select source_ip, dest_ip, sum(time), sum(sent_bytes) group by source_ip, dest_ip

Categories