Impersonate a server - java

Here is my probelm: I have an Android application that communicates with an API on a specific server, which has the IP address IP_Server, through HTTP messages and using SSL. I want to impersonate the API and receive the messages from the application (from one of my smartphone) on my computer and respond to them as I want (according to the API protocol). To do so, in my router, I redirect the route for the IP_Server to my local network and I assign the IP_Server IP address to my computer. Then, I run a Java Server that listens on the port 443 using SSLSocket. At this stage, I receive the connection request when the application wants to communicate. However, the handshake fails. I think that it’s a certificate problem but I’m not sure and I don’t know how to resolve this issue.
public static void startServer() throws Exception
{
SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket sslserversocket = (SSLServerSocket) sslserversocketfactory.createServerSocket(443);
while (running)
{
// Listen.
SSLSocket clientSocket = (SSLSocket)sslserversocket.accept();
System.out.println("Connection accepted from:" +
clientSocket.toString());
clientSocket.startHandshake(); // This line causes a timeout.
// Handle the request.
threadPool.execute(new ServerThread(clientSocket));
}
}
Thanks for your help!

Related

Chat using TCP in Java

I am making a chat in Java which uses a TCP protocol.
I have a client and a server side.
To send a message to another user, I have to send the message to the server through my client, and the server has to send it to another client.
The server holds the addresses of both online users. When I send a private message, the server finds the ip and a port and creates a socket from them.
The problem is that it doesn’t work correctly.
Here’s the code:
int portNumber = 4444;
String host = "192.168.0.100”;
Socket link;
try {
link = new Socket(host, portNumber);
// Then I set to already created PrintWriter the outputstream
out = new PrintWriter(link.getOutputStream(), true);
} catch (Exception e) {}
// Unfortunately the server freezes here (it doesn't show anything).
How to solve this problem? Where dod I make a mistake?
Thank you in advance.
You shouldn't create a new Socket to send a message. Instead, use a socket of an existing connection.
The sequence should be the following:
Client A connects to the server (server stores the connection as SocketA).
Client B connects to the server (server stores the connection as SocketB).
Server reads a private message from SocketA. The message is addressed to client B.
Server finds the existing socket for client B. It's SocketB.
Server sends the message into SocketB.

Netty Proxy server

I have the read the netty proxy server example. However I would like to know how to implement a client to talk to the proxy. The solution I am implementing is a server and it needs to connect to a socket server whenever a client connect to the server.So each client connected to the server will be able to send/receive data from another server.
I need help to inplement such architecture with netty because the server side is built on netty.
It seems what you want to implement can be pretty much answered by the Netty proxy example
The code segment below shows how you can connect to the remote server once a new client channel is opened.
#Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
// Suspend incoming traffic until connected to the remote host.
final Channel inboundChannel = e.getChannel();
inboundChannel.setReadable(false);
// Start the connection attempt.
ClientBootstrap cb = new ClientBootstrap(cf);
cb.getPipeline().addLast("handler", new OutboundHandler(e.getChannel()));
ChannelFuture f = cb.connect(new InetSocketAddress(remoteHost, remotePort));
outboundChannel = f.getChannel();
f.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
// Connection attempt succeeded:
// Begin to accept incoming traffic.
inboundChannel.setReadable(true);
} else {
// Close the connection if the connection attempt has failed.
inboundChannel.close();
}
}
});
}
Once connected to the remote server, whatever the client sends (via inbound channel) is forwarded to the remote server (outbound channel).
I suggest you to follow and implement the proxy example if you haven't done it so already.

Socket in java and nmap

I have program write it in java it's wait a connection on port
when I scan the server by nmap the program is stop (erorr)
this is my code
SSLServerSocketFactory sslServerSocketfactory = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
sslServerSocket = (SSLServerSocket)sslServerSocketfactory.createServerSocket(intSSLport);
out = new PrintWriter(sslSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
String value = in.readLine();
thanks jtahlborn ,,,, I solved by using try and catch ,,, and make catch return to
sslSocket = (SSLSocket)sslServerSocket.accept()
again
nmap is scanning open ports, by trying to connect to them (sending TCP SYN).
Since you've opened server socket, it returns when there's a client connecting to it.
In your case it's nmap, which tries to connect.
AFAIK, nmap won't complete TCP connection procedure (3 way handshake). nmap will receive TCP SYN/ACK sent as result of your call to accept(), and will conclude the port is open.
That it's all, nmap won't send 3rd message required to complete TCP connection procedure (ACK).

Netty is giving me a wrong port using TCP

I'm using Netty with Java trying to configure a TCP client. Everything is working so far, except that I'm connecting on port 1050 but when I call messageEvent.getRemoteAddress() on messageReceived() method of the handler, I'm getting the port 1500. I changed the port to 1049 but I'm still receiving 1500. This is Netty's problem or can it be the server's problem?
My hardware setup here is: this netty client running on a Java server, and several access control equipments spread through the area here. The equipments act as tcp servers and the netty as the client, that process everything the server sends and just reply to them.
The tcp server initialization is this:
private ChannelFactory fabrica;
private ServerBootstrap bootstrap;
public void iniciarServidorTCP() {
fabrica = new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
bootstrap = new ServerBootstrap(fabrica);
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
#Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoderDeMensagem", new MensagemDecoderTCP());
pipeline.addLast("handlerGerente", new GerenteTCP());
pipeline.addLast("encoder de mensagem", new MensagemEncoderTCP());
return pipeline;
}
});
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.reuseAddress", true);
bootstrap.bind(new InetSocketAddress(1050));
}
Any idea why I'm getting 1500 instead of 1050? Could it be a problem with the equipment?
Every TCP connection has a source port and a destination port. When you connect to a server, the server sees the destination port as its well-known address. The client picks the source port. On either end, getting the "remote address" gets the other side's address. So when you call get remote address on the server, you get the client's address, not the server's.
Imagine you have a server with one IP address and one well-known port. Now, say you have a client machine with one IP address. If it make's four connections to the server, how can either end tell those connections apart? The answer is that the client port is different.

How a threaded server continues to listen on the post for more incoming connections?

I am going through Sun's Java tutorial. I am in the lesson about sockets. There is the following code for a simple threaded server:
import java.net.*;
import java.io.*;
public class KKMultiServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(-1);
}
while (listening)
new KKMultiServerThread(serverSocket.accept()).start();
serverSocket.close();
}
}
The server is said to "keep listening for more incoming connections". I just don't understand how it's possible; the line serverSocket.accept() constructs a new (client) Socket object which is, according to the tutorial "bound to the same local port and has its...". Well, how is it possible that the server is communicating with the client and listening to more incoming connections on the same port? As far as I know, if a port is used for some connection it is blocked and cannot be used for more things.
So what am I getting wrong here?
Well, a socket is not one-to-one based on a port, it is unique on a tuple of (address, port). A connection - the pair of the local and remote sockets involved in the communication - is used to demux incoming data from a port to the correct socket, allowing multiple sockets on one port. See Wikipedia. In other words, the relationship of sockets to ports are N-to-1
getting multiple connections on the same port is entirely possible as each TCP connection is a (local host, local port, remote host, remote port) tuple as long as at least 1 is different the connections are distinct and won't interfere (besides bandwidth drops)
clients attempting to connect to a server generally get a port assigned from the OS that is not used currently
Listening sockets work like a receptionist in on a business's phone switch. Everyone calls the switch number, and the receptionist responds to each incoming call on the switch line by having someone else handle the call on another line. Even though the receptionist can only take one call at a time, the switch line is tied up only very briefly because it is used only to establish a connection.
[...]TCP demultiplexes incoming segments using all four values that comprise the local and foreign addresses: destination IP address, destination port number, source IP address, and source port number. TCP cannot determine which process gets an incoming segment by looking at the destination port only. Also, the only one of the [various] endpoints at [a given port number] that will receive incoming connection requests is the one in the listen state. (p255, TCP-IP Illustrated Volume 1, W. Richard Stevens)
The last sentence in the above quote is the key to understanding.
Interestingly, a socket isn't really identified by the combination of IP address and port. This is unique only in context, where the context is either a particular connection or the listening state. Only one listener socket can bind to a particular IP/port combination.
The short and sweet answer is that the port is blocked for OTHER programs and processes. Only the program that opened the port can now listen on it. BUT it can listen to many different clients on the same port.
When a client connects, it creates a unique socket. A socket is comprised of the listening IP address and port (the one you opened) AND the calling IP address and port. Because the caller's IP address and port are always unique, each socket is unique and identifiable to your listener.
Even if I connected to your program twice from the same machine, my machine would select a new and random source port for each connection -- thus ensuring that we have a unique socket each time.
Based on this link
The accept method waits until a client starts up and requests a connection on the host and port of this server (in this example, the server is running on the hypothetical machine taranis on port 4444). When a connection is requested and successfully established, the accept method returns a new Socket object which is bound to the same local port and has its remote address and remote port set to that of the client.The server can communicate with the client over this new Socket and continue to listen for client connection requests on the original ServerSocket This particular version of the program doesn't listen for more client connection requests.
Here is SO discussion which may clear confusion about how single port handles multiple client calls Port and Socket SO discussion .
To put it in simple terms, most of the webservers listen on port 8080 and multiple clients will access same port to access your website.

Categories

Resources