I have a small Java program that reads list of IPs from text file and inside a loop it create ssl session with the ip. The session might succeed or fail depend whether the port 443 is enabled in the other side or not.
My problem:
1. If port 443 is not enabled in the other side, the session will fail. The problem is that my program stops here and go to exception handling and print me the error and ends. I want the program to continue creating the next session with the next IP and so on. How can I make it continue and print out a message saying that the session failed for that IP?
Another issue: How can I get the enabled cipher suite? I tried to print socket.getEnabledCipherSuites(); but printed strange text not a type of cipher suite at all.
EDIT:
public static void main(String[] argv) {
try{
while ((there are IPs)
{
try{
//call for Connect function which has try/catch on it the same way
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}//catch
}//end while loop
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}//catch
}//end void main </i>
your point #1 seems to be something exception handling should take care of: enclose each iteration on all_ips within its own try/catch block.
You could greatly benefit from some multithreading and time-out here, as some firewall will just drop your SYN packet silently and let your scanner tool wait indefinitely.
BUT before you do that, take care: you're going to look very much like a malicious tool scanning a network for some vulnerabilities. You may get into administrative trouble if you're too aggressive or target someone you don't know. A pool of thread or some similar technique to ensure you're not exceeding fair amount of connection establishment/second is a bare minimum.
Related
The title basically says it all but just but to reiterate:
I need my Java program to kill itself (dispose w/e) if a specific external program launches.
My java program uses a global hook that listens for mouse input, when I remote into a clients computer the mouse listener/GUI that my program creates can cause all kinds of issues with the mouse if used I'm while connected. To handle this I need my program to automatically "turn off" when the screen-connect application we use launches.
I am already using a global hook to capture mouse input, is there something similar I could use for system events maybe?
Depending on the version of windows respectively Java you are using there are various libraries you could be using to simply regularly "scan" the operating system for a list of running processes.
If something shows up that you don't like, simply react using System.exit for example.
In your first program, just create a new Thread and let it run. Put this code in the run method:
try {
ServerSocket socket = new ServerSocket(1111); // the paramater is a port and you can choose any port you want
socket.accept();
socket.close();
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
This will wait for a connection and once the connection is made, it will close itself. That is because the accept method that waits for a connection blocks until there is a connection made. That's why you put it in another thread.
After it recieves the connection it will unblock so the code will continue and exit the program! And it MUST be in another friend so it doesn't block your application!
In the second application, in the beginning just make a connection!
To make a connection use this code:
try (Socket socket = new Socket("localhost" ,1111);){
socket.close();
} catch (IOException e) {
}
This will connect it and once it does, the first program will close. Now just continue on with this program! If you don't understand the sockets the best, then check out this link. It is awesomely explained:
https://www.javaworld.com/article/2077322/core-java/core-java-sockets-programming-in-java-a-tutorial.html
I'm having a problem with one of my servers, on Friday morning I got the following IOException:
11/Sep/2015 01:51:39,524 [ERROR] [Thread-1] - ServerRunnable: IOException:
java.io.IOException: Too many open files
at sun.nio.ch.ServerSocketChannelImpl.accept0(Native Method) ~[?:1.7.0_75]
at sun.nio.ch.ServerSocketChannelImpl.accept(ServerSocketChannelImpl.java:241) ~[?:1.7.0_75]
at com.watersprint.deviceapi.server.ServerRunnable.acceptConnection(ServerRunnable.java:162) [rsrc:./:?]
at com.watersprint.deviceapi.server.ServerRunnable.run(ServerRunnable.java:121) [rsrc:./:?]
at java.lang.Thread.run(Thread.java:745) [?:1.7.0_75]
Row 162 of the ServerRunnable class is in the method below, it's the ssc.accept() call.
private void acceptConnection(Selector selector, SelectionKey key) {
try {
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel sc = ssc.accept();
socketConnectionCount++;
/*
* Test to force device error, for debugging purposes
*/
if (brokenSocket
&& (socketConnectionCount % brokenSocketNumber == 0)) {
sc.close();
} else {
sc.configureBlocking(false);
log.debug("*************************************************");
log.debug("Selector Thread: Client accepted from "
+ sc.getRemoteAddress());
SelectionKey newKey = sc.register(selector,
SelectionKey.OP_READ);
ClientStateMachine clientState = new ClientStateMachine();
clientState.setIpAddress(sc.getRemoteAddress().toString());
clientState.attachSelector(selector);
clientState.attachSocketChannel(sc);
newKey.attach(clientState);
}
} catch (ClosedChannelException e) {
log.error("ClosedChannelException: ", e);
ClientStateMachine clientState = (ClientStateMachine)key.attachment();
database.insertFailedCommunication(clientState.getDeviceId(),
clientState.getIpAddress(),
clientState.getReceivedString(), e.toString());
key.cancel();
} catch (IOException e) {
log.error("IOException: ", e);
}
}
How should I handle this? reading up on the error it appears to be a setting in the Linux OS that limits the number of open files a process can have.
Judging from that, and this question here, it appears that I am not closing sockets correctly (The server is currently serving around 50 clients). Is this a situation where I need a timer to monitor open sockets and time them out after an extended period?
I have some cases where a client can connect and then not send any data once the connection is established. I thought I had handled those cases properly.
It's my understanding that a non-blocking NIO server has very long timeouts, is it possible that if I've missed cases like this they might accumulate and result in this error?
This server has been running for three months without any issues.
After I go through my code and check for badly handled / missing cases, what's the best way to handle this particular error? Are there other things I should consider that might contribute to this?
Also, (Maybe this should be another question) I have log4j2 configured to send emails for log levels of error and higher, yet I didn't get an email for this error. Are there any reasons why that might be? It usually works, the error was logged to the log file as expected, but I never got an email about it. I should have gotten plenty as the error occurred every time a connection was established.
You fix your socket leaks. When you get EOS, or any IOException other than SocketTimeoutException, on a socket you must close it. In the case of SocketChannels, that means closing the channel. Merely cancelling the key, or ignoring the issue and hoping it will go away, isn't sufficient. The connection has already gone away.
The fact that you find it necessary to count broken socket connections, and catch ClosedChannelException, already indicates major logic problems in your application. You shouldn't need this. And cancelling the key of a closed channel doesn't provide any kind of a solution.
It's my understanding that a non-blocking NIO server has very long timeouts
The only timeout a non-blocking NIO server has is the timeout you specify to select(). All the timeouts built-in to the TCP stack are unaffected by whether you are using NIO or non-blocking mode.
I am working on socket programming and implementing custom request response protocol. For same I have used ObjectInputstream and ObjectOutputstream in java socket API.
The area where I have stucked is to check if data(in my case object) is available to read or not, for this I have tried to use the ObjectInputstream.available() but it is returning 0 even if data is available on stream.
Why is it so?
So I have come up with solution: using exception and handling them in infinitely running loop, so even if exception(Read time out) occurs it will try to read again.
I have doubt is it good practice to do so? Or if any other solution you might have do suggest.
while (true){
try {
request = rpcClient.getRequest();
System.out.println(request);
// use threads to handle request for faster response(make use of request IDs)
rpcClient.sendResponse("test response");
} catch (SocketException e)
{// thrown when connection reset
System.out.println("Connection reset : Server is down.....");
break;
} catch (IOException e){
// thrown when read time out
System.out.println("read time out: listening again");
} catch (ClassNotFoundException e){
e.printStackTrace();
}
}
You shouldn't be using available() in the first place. Disable the read timeout, so you can just let the thread wait until there's something to read (or the connection is broken).
I wouldn't recommend using ObjectStreams for network communications though. It's not very suitable in most cases, considering the header information and other things that gets transferred. You're better off designing your own protocol to use and just send bytes over the network.
That is not a good practice since an infinite loop eats away your CPU time.
I dont quite understand your statement
but it is returning 0 even if data is available on stream
since that isnt the case. If it returns 0, there is no data that can be read from the stream. What makes you so sure there actually is data?
Also: I cant see the code that is calling available(). Could you edit your question?
I have an assignment where I basically have to write a small botnet. We have been given a list of usernames and encrypted passwords. We have also been given the code to decrypt these passwords. The assignment is to use TCP to crack the passwords in a Master/Slave relationship. The password cracking is like a Dictionary attack in which you compare the encrypted passwords to a dictionary.
This means that a Master (Server) have to send instructions out to Slaves (Clients). These instructions are encrypted passwords, and where in the diciontary to start looking so that different slaves can check different parts of the dicionary at the same time, speeding up the process of decrypting.
Personally I have to take care of the Master. The process works as such:
A Master (Class) starts a Session (Class implementing Runnable) in a new Thread. The Session makes individual InputStreamListeners (Class implementing Runnable) for each Slave so that input can be handled on separate threads. When the Slave is done, all the decrypted passwords are sent to the InputStreamListener and added to an ArrayList of strings. This list will then be sent to the Session, and hopefully added to a list of ArrayLists (so ArrayList>). The Session do receive all the passwords. The Socket gets closed in the InputStreamListener and the Slave shuts down. This to me, would mean that the task for that listener should now be shutdown, and not be in the ExecutorService thread pool any more.
We have only been working with 1 slave at a time, so far. When the InputStreamListener close ends, the code looks like this:
try {
writer.println("Disconnecting Slave...");
scanner.close();
writer.close();
slave.getSocket().close();
Master.messageServer("Slave Socket Close");
} catch (IOException ex) {
Master.messageServer("[" + ip + "]: Problem closing Socket for Slave: ");
Master.messageServer("[" + ip + "]:" + ex.getMessage());
}
while(true) {
Master.messageServer("Trying Lock");
if(session.lock.tryLock()) {
try {
session.addResults(results);
Master.messageServer("Added Results to Session.");
break;
} finally {
session.lock.unlock();
}
}
}
The InputStreamListener reaches the while loop but only prints "Trying Lock" once. If it was locked this means that the Console should now be spammed with "Trying Lock" until it can actually reach the method and then print "Added results to Session".
The code in the session looks like this:
public void addResults(ArrayList<String> list) {
lock.lock();
try {
results.add(list);
} finally {
lock.unlock();
}
}
The lock is a ReentrantLock.
This is of course done, so that 2 or more InputStreamListeners don't access the method at the same time.
I simply can't find out why this happens, and why the program won't work. Logically it seems to be working. Other than this, it just puts the information into a new method to create a txt file. Help?
I'm creating a small server using java.nio, but when trying to stress test it I keep getting messages about the connection being reset on the server side, or more specifically:
apr_socket_recv: An established connection was aborted by the software in your host machine
I've tried to narrow it down to the most simple of loops, but still no luck. I can get the error after a hundred or so connections, or maybe just after 1 or 2.
Here's the server loop:
byte[] response = ("HTTP/1.1 200 OK\r\n"
+ "Server: TestServer\r\n"
+ "Content-Type: text/html\r\n"
+ "\r\n"
+ "<html><b>Hello</b></html>").getBytes();
SocketChannel newChannel = null;
while (active) {
try {
//get a new connection and delegate it.
System.out.print("Waiting for connection..");
newChannel = serverSocketChannel.accept();
System.out.println("ok");
newChannel.configureBlocking(true);
newChannel.write(ByteBuffer.wrap(response));
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
newChannel.close();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I've tried checking if the write didn't write all requested byte, but it seemingly does. Interestingly enough, calling System.gc() after each newChannel.close() makes the problem disappear (but in return, it's horribly slow). So either I'm not releasing all resources I should release, or the application just needs a pause..
I'm losing all of my best years on this. Oh, and by the way.. if I ignore writing to the channel and just close after I accept the connection, the problem still doesn't go away.
Well I found it out, so I might as well share it.
My app needed a pause. It was simply going too fast, and closing the connection before the client had written all of its request data. The fix would be to keep on reading until the entire HTTP request had been received. D'oh.. lesson learned.
From the docs for SocketChannel#Write (emphasis mine):
An attempt is made to write up to r bytes to the channel, where r is
the number of bytes remaining in the buffer, that is, src.remaining(),
at the moment this method is invoked.
[...]
Returns: The number of bytes written, possibly zero.
It's up to you to check the return value from the write call (which you're not doing presently), and issue successive write calls until the whole of the buffer has been sent. Something like this, I guess:
ByteBuffer toWrite = ByteBuffer.wrap(response);
while (toWrite.remaining() > 0) {
newChannel.write(toWrite);
}
You'll obviously get aborts if you don't write all of your response data and then just close the socket.