Commit 5a62e3e4 by michaelpastushkov
parents 8ea0095a 0e0ac9ea
/*
* Copyright (C) 2024 Michael Pastushkov <michael@pastushkov.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
*/
import java.net.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class ByteVia {
private static final int MAX_UDP_CLIENTS = 10;
private byte[] cipher = new byte[256];
private int cipherTime;
private Options options = new Options();
private DatagramSocket udpSocket;
private ServerSocket tcpSocket;
private Map<InetAddress, Integer> clients = new HashMap<>();
public static void main(String[] args) {
ByteVia server = new ByteVia();
server.initOptions();
server.run();
}
public void initOptions() {
// Initialize default options
options.localPort = 1948;
options.bindAddress = "0.0.0.0";
options.remoteHost = "p4pn.net";
options.remotePort = 1984;
options.bufferSize = 4096;
options.encrypt = false;
options.log = true;
options.secret = 52341;
options.proto = "tcp";
options.mode = "client";
}
public void run() {
try {
if (options.log) {
System.out.println("NetVia Java");
System.out.println(" proto: " + options.proto);
System.out.println(" local: " + options.bindAddress +":"+ options.localPort);
System.out.println(" remote: " + options.remoteHost +":"+ options.remotePort);
System.out.println(" mode: " + options.mode);
System.out.println(" encrypt: " + options.encrypt);
}
if (options.proto == "udp") {
udpSocket = new DatagramSocket(options.localPort);
System.out.println("UDP server started on port " + options.localPort);
udpServerLoop();
} else {
tcpSocket = new ServerSocket(options.localPort);
System.out.println("TCP server started on port " + options.localPort);
tcpServerLoop();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void udpServerLoop() {
byte[] buffer = new byte[options.bufferSize];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
try {
udpSocket.receive(packet);
InetAddress clientAddress = packet.getAddress();
int clientPort = packet.getPort();
System.out.println(getCurrentTimestamp() + " Received packet from " + clientAddress);
// Add client to list if not already
if (!clients.containsKey(clientAddress)) {
clients.put(clientAddress, clientPort);
}
// Process data (encryption simulation)
if (options.encrypt) {
updateCipher();
for (int i = 0; i < packet.getLength(); i++) {
buffer[i] = cipher[buffer[i] & 0xFF];
}
}
// Echo back the processed data
DatagramPacket response = new DatagramPacket(buffer, packet.getLength(), clientAddress, clientPort);
udpSocket.send(response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void tcpServerLoop() {
while (true) {
try {
Socket clientSocket = tcpSocket.accept();
System.out.println(getCurrentTimestamp() + " Accepted connection from " + clientSocket.getInetAddress());
new Thread(() -> handleTcpClient(clientSocket)).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void handleTcpClient(Socket clientSocket) {
try {
Socket remoteSocket = new Socket();
remoteSocket.connect(new InetSocketAddress(options.remoteHost, options.remotePort));
System.out.println("Connected to remote server at " + options.remoteHost + ":" + options.remotePort);
InputStream in = clientSocket.getInputStream();
OutputStream out = remoteSocket.getOutputStream();
InputStream in2 = remoteSocket.getInputStream();
OutputStream out2 = clientSocket.getOutputStream();
byte[] buffer = new byte[options.bufferSize];
int bytesRead;
while (true) {
if (in.available() > 0) {
bytesRead = in.read(buffer);
if (bytesRead == -1)
break;
System.out.println(" From client " + bytesRead + " bytes");
// Process data (encryption simulation)
if (options.encrypt) {
updateCipher();
for (int i = 0; i < bytesRead; i++) {
buffer[i] = cipher[buffer[i] & 0xFF];
}
}
out.write(buffer, 0, bytesRead);
out.flush();
System.out.println(" Sent");
}
/*******/
if (in2.available() > 0) {
bytesRead = in2.read(buffer);
if (bytesRead == -1)
break;
System.out.println(" From remote " + bytesRead + " bytes");
out2.write(buffer, 0, bytesRead);
out2.flush();
System.out.println(" Sent");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void updateCipher() {
int currentTime = getTime();
if (currentTime == cipherTime) {
return;
}
Random random = new Random(currentTime);
for (int i = 0; i < 256; i++) {
cipher[i] = (byte) i;
}
for (int i = 255; i > 0; i--) {
int j = random.nextInt(i + 1);
byte temp = cipher[i];
cipher[i] = cipher[j];
cipher[j] = temp;
}
cipherTime = currentTime;
System.out.println(getCurrentTimestamp() + " Updated cipher.");
}
private int getTime() {
return (int) (System.currentTimeMillis() / (60 * 10 * 1000));
}
private String getCurrentTimestamp() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(new Date());
}
static class Options {
int localPort;
String bindAddress;
String remoteHost;
int remotePort;
int bufferSize;
boolean encrypt;
boolean log;
int secret;
String proto;
String mode;
}
}
/*
* Copyright (C) 2024 Michael Pastushkov <michael@pastushkov.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
*/
import java.net.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.time.Instant;
import java.nio.ByteBuffer;
import java.util.Iterator;
import java.nio.channels.*;
import java.util.Set;
import java.nio.channels.spi.*;
public class ByteVia {
private static final int MAX_UDP_CLIENTS = 10;
private byte[] cipher = new byte[256];
private Options options = new Options();
private DatagramSocket udpSocket;
private ServerSocket tcpSocket;
private Map<InetAddress, Integer> clients = new HashMap<>();
private int cipherTime = -1;
public static void main(String[] args) {
ByteVia bytevia = new ByteVia();
bytevia.initOptions();
bytevia.run();
}
public void initOptions() {
// Initialize default options
options.localPort = 1948;
options.bindAddress = "0.0.0.0";
options.remoteHost = "p4pn.net";
options.remotePort = 1984;
options.bufferSize = 4096;
options.encrypt = true;
options.log = 1;
options.secret = 52341;
options.proto = "tcp";
options.mode = "client";
}
public void run() {
if (options.log > 0) {
System.out.println("NetVia Java");
System.out.println(" proto: " + options.proto);
System.out.println(" local: " + options.bindAddress +":"+ options.localPort);
System.out.println(" remote: " + options.remoteHost +":"+ options.remotePort);
System.out.println(" mode: " + options.mode);
System.out.println(" encrypt: " + options.encrypt);
}
try {
tcpServerLoop();
} catch (Exception e) {
e.printStackTrace();
}
}
private void tcpServerLoop() {
try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(1948));
while (true) {
SocketChannel clientChannel = serverSocketChannel.accept();
System.out.println("Accepted connection");
handleTcpClient(clientChannel);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void handleTcpClient(SocketChannel clientChannel) {
try {
SocketChannel remoteChannel = SocketChannel.open();
remoteChannel.connect(new InetSocketAddress(options.remoteHost, options.remotePort));
System.out.println("Connected to remote server at " + options.remoteHost + ":" + options.remotePort);
ByteBuffer buffer = ByteBuffer.allocate(options.bufferSize);
Selector selector = SelectorProvider.provider().openSelector();
clientChannel.configureBlocking(false);
remoteChannel.configureBlocking(false);
clientChannel.register(selector, SelectionKey.OP_READ, "client");
remoteChannel.register(selector, SelectionKey.OP_READ, "remote");
while (true) {
selector.select();
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectedKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
if (key.isReadable()) {
// Check which channel is ready and read data
SocketChannel channel = (SocketChannel) key.channel();
String streamId = (String) key.attachment();
buffer.clear();
int bytesRead = channel.read(buffer);
if (bytesRead > 0) {
System.out.println("Data read from " + streamId + ", bytes: " + bytesRead);
buffer.flip();
byte[] data = new byte[buffer.position()];
buffer.flip(); // Switch buffer to reading mode
buffer.get(data); // Transfer buffer content to byteArray
if (streamId == "client") {
encode(data);
buffer = ByteBuffer.wrap(data);
buffer.flip();
while(buffer.hasRemaining()) {
remoteChannel.write(buffer);
}
} else {
decode(data);
buffer = ByteBuffer.wrap(data);
buffer.flip();
while(buffer.hasRemaining()) {
clientChannel.write(buffer);
}
}
} else if (bytesRead == -1) {
// End of stream, close the channel
key.cancel();
channel.close();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private int xorshift32(int[] state) {
int x = state[0];
x ^= (x << 13);
x ^= (x >>> 17); // Unsigned right shift
x ^= (x << 5);
state[0] = x;
//System.out.printf("xor: %d \n", x);
return x;
}
private void shuffle(byte[] array, int seed) {
int n = array.length;
int[] state = new int[1];
state[0] = seed;
for (int i = n - 1; i > 0; i--) {
int x = xorshift32(state);
int j = (x & 0xFFFFFFFF) % (i + 1);
System.out.printf("x: %s, j: %s, i: %s \n", Integer.toBinaryString(x), Integer.toBinaryString(j), Integer.toBinaryString(i));
byte temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
private int getHash(int source) {
int hash = source;
hash = (hash ^ 61) ^ (hash >>> 16); // Unsigned right shift
hash = hash + (hash << 3);
hash = hash ^ (hash >>> 4); // Unsigned right shift
hash = hash * 0x27d4eb2d;
hash = hash ^ (hash >>> 15); // Unsigned right shift
return hash;
}
private int getTime() {
long now = Instant.now().getEpochSecond(); // Get current time in seconds since UNIX epoch
return (int) (now / (60 * 10)); // Change cipher every 10 minutes
}
private void updateCipher() {
int time = getTime();
if (time == cipherTime) {
return;
}
for (int i = 0; i < 256; i++) {
cipher[i] = (byte) i;
}
int seed = getHash(options.secret * time);
shuffle(cipher, seed);
if (options.log > 1) {
System.out.println(" new cipher " + time);
if (options.log > 2) {
for (int i = 0; i < 256; i++) {
System.out.print(cipher[i] + " ");
if ((i + 1) % 16 == 0) {
System.out.println();
}
}
}
}
cipherTime = time;
}
private int encode(byte[] buf) {
if (!options.encrypt)
return 0;
updateCipher();
int len = buf.length;
for (int i = 0; i < len; i++) {
buf[i] = cipher[buf[i] & 0xFF]; // Ensure byte is treated as unsigned
}
if (options.log > 0) {
System.out.printf("\r%-50s", " ");
System.out.printf("\r%s encode %d bytes ", getCurrentTimestamp(), len);
System.out.flush();
}
return 0;
}
private int decode(byte[] buf) {
if (!options.encrypt) {
return 0;
}
updateCipher();
int len = buf.length;
for (int i = 0; i < len; i++) {
for (int j = 0; j < 256; j++) {
if (cipher[j] == buf[i]) {
buf[i] = (byte) j;
break;
}
}
}
if (options.log > 0) {
System.out.printf("\r%-50s", " ");
System.out.printf("\r%s decode %d bytes ", getCurrentTimestamp(), len);
System.out.flush();
}
return 0;
}
private String getCurrentTimestamp() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(new Date());
}
static class Options {
String proto;
int localPort;
String bindAddress;
String remoteHost;
int remotePort;
int bufferSize;
boolean encrypt;
int log;
int secret;
String mode;
}
}
javac bytevia.java && java ByteVia
#!/bin/sh #!/bin/sh
make clean && make && ./bytevia --local-port=1948 --remote-host=p4pn.net --remote-port=1984 --proto=tcp make clean && make && ./bytevia --local-port=1948 --remote-host=p4pn.net --remote-port=1984 --proto=tcp --encrypt=1
...@@ -90,7 +90,7 @@ unsigned int xorshift32(unsigned int *state) ...@@ -90,7 +90,7 @@ unsigned int xorshift32(unsigned int *state)
void shuffle(unsigned char *array, int n, unsigned int seed) void shuffle(unsigned char *array, int n, unsigned int seed)
{ {
unsigned int state = seed; unsigned int state = seed;
srand(seed); // srand(seed);
for (int i = n - 1; i > 0; i--) for (int i = n - 1; i > 0; i--)
{ {
int j = xorshift32(&state) % (i + 1); int j = xorshift32(&state) % (i + 1);
...@@ -438,7 +438,9 @@ int use() ...@@ -438,7 +438,9 @@ int use()
} }
/* Processing request from local, sending it to remote*/ /* Processing request from local, sending it to remote*/
count_recv = (options.proto == SOCK_DGRAM) ? recvfrom(rc.client_socket, buffer, sizeof(buffer), 0, (struct sockaddr *)&client_addr, &addr_len) : recv(rc.client_socket, buffer, sizeof(buffer), 0); count_recv = (options.proto == SOCK_DGRAM) ?
recvfrom(rc.client_socket, buffer, sizeof(buffer), 0, (struct sockaddr *)&client_addr, &addr_len) :
recv(rc.client_socket, buffer, sizeof(buffer), 0);
if (count_recv < 0) if (count_recv < 0)
{ {
...@@ -463,7 +465,8 @@ int use() ...@@ -463,7 +465,8 @@ int use()
send(rc.remote_socket, buffer, count_recv, 0); send(rc.remote_socket, buffer, count_recv, 0);
if (options.log > 1) if (options.log > 1)
printf("recv %d\t%s:%d\tpid: %d\n", count_recv, inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), getpid()); printf("recv %d bytes from %s:%d, pid: %d\n",
count_recv, inet_ntoa(rc.client_addr.sin_addr), ntohs(rc.client_addr.sin_port), getpid());
} }
if (FD_ISSET(rc.remote_socket, &io)) if (FD_ISSET(rc.remote_socket, &io))
...@@ -493,7 +496,8 @@ int use() ...@@ -493,7 +496,8 @@ int use()
send(rc.client_socket, buffer, count_recv, 0); send(rc.client_socket, buffer, count_recv, 0);
if (options.log > 1) if (options.log > 1)
printf("sent %d\t%s:%d\tpid: %d\n", count_recv, inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), getpid()); printf("sent %d byets to %s:%d, pid: %d\n",
count_recv, inet_ntoa(rc.client_addr.sin_addr), ntohs(rc.client_addr.sin_port), getpid());
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment