GithubHelp home page GithubHelp logo

sockslib's Introduction

SocksLib Build Status Coverage Status Coverity Scan Build Status

SocksLib is a Java library for SOCKS5 protocol.

See Java API Documentation

See Wiki Page (Chinese)

If you are looking for a SOCKS5 server instead of a SOKCS5 library, I hope Esocks can help you.

References

Features

Client

  • TCP proxy
  • UDP proxy
  • Bind
  • Anonymous authentication
  • USERNAME/PASSWORD authentication
  • Proxy chain

Server

  • TCP proxy
  • UDP proxy
  • Bind
  • Anonymous authentication
  • USERNAME/PASSWORD authentication
  • Proxy chain
  • Black or white IP lists for clients

Quick start

Environment

  • JDK 8+

Dependencies

You should put following libraries in your project's CLASSPATH:

SOCKS5 Client

CONNECT

    SocksProxy proxy = new Socks5(new InetSocketAddress("localhost",1080));
    Socket socket = new SocksSocket(proxy, new InetSocketAddress("whois.internic.net",43));

Connect SOCKS5 server using SSL connection

    SSLConfigurationBuilder builder = SSLConfigurationBuilder.newBuilder();
    builder.setTrustKeyStorePath("client-trust-keystore.jks");
    builder.setTrustKeyStorePassword("123456");
    SocksProxy proxy = new SSLSocks5(new InetSocketAddress("localhost", 1081), builder.build());
    Socket socket = new SocksSocket(proxy, new InetSocketAddress("whois.internic.net",43));

BIND

    SocksServerSocket serverSocket = new SocksServerSocket(proxy, inetAddress,8080);
    InetAddress bindAddress = serverSocket.getBindAddress();
    int bindPort  = serverSocket.getBindPort();
    Socket socket = serverSocket.accept();

UDP ASSOCIATE

     DatagramSocket socket = new Socks5DatagramSocket(proxy);

SOCKS5 Server

     SocksProxyServer proxyServer = SocksServerBuilder.buildAnonymousSocks5Server(); 
     proxyServer.start();// Creat a SOCKS5 server bind at port 1080

SSL socks server

    SSLConfigurationBuilder builder = SSLConfigurationBuilder.newBuilder();
    builder.setKeyStorePath("server-keystore.jks");
    builder.setKeyStorePassword("123456");
    builder.setClientAuth(false);
    socksProxyServer = SocksServerBuilder.buildAnonymousSSLSocks5Server(1081, builder.build());
    socksProxyServer.start();

sockslib's People

Contributors

dependabot[bot] avatar fengyouchao avatar gamerson avatar ivanfmartinez avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sockslib's Issues

Socks5DatagramSocket fails to redefine connect

When trying to use DatagramSocket.connect on a derived Socks5DatagramSocket, you will run into IllegalArgumentException "connected address and packet address differ". This is because the connect method is not overloaded to connect to the relayInetSocketAddress. This way, the socket is actually connected to the final destination address, leading to an address conflict with the encapsulated DatagramPacket.
To fix, overload connect() to transparently connect to relayInetSocketAddress instead. Additionally, you should store the InetSocketAddress given to connect by the caller and check equals in the overloaded send methods.

安卓设备内存溢出问题及解决方法

It crashes due to a stack-over-flow problem everytime when I used the library as a socks5server running on Android device。Which is caused by the frequently allocated byte[] buffer using in StreamPipe.java。

I fixed this problem in two steps:

  1. reduce the byte[] buffer in StreamPipe.java to 256960
  2. use a BufferPool to allocate new buffer, witch can automatically deallocate memory when the buffer nums meet the setting max.

the BufferPool I used:

class BufferPool {
private static final int BUFFER_SIZE = 256960;     //缓冲包2M
private static final int BUFFER_MAX_NUM = 40;                   //缓冲池保留最大数量
private static final ConcurrentLinkedQueue<byte[]> buffers = new ConcurrentLinkedQueue<byte[]>();
private static AtomicInteger countCreated = new AtomicInteger(0);   //已创建的缓冲包个数

/**
 * 分配
 */
public static byte[] allocate() {
    byte[] result = buffers.poll();
    //创建新缓冲包
    if (result == null) {
        result = new byte[BUFFER_SIZE];

        //记录创建个数
        int count = countCreated.incrementAndGet();

        //日志
        if (count <= BUFFER_MAX_NUM) {
            logger.info("创建新的BufferPool缓冲池,已创建总数量:count={}", count);
        } else {
            logger.warn("创建新的BufferPool缓冲池,已创建总数量:count={}", count, new Throwable());
        }
    }
    return result;
}

/**
 * 回收
 *
 * @param buff
 */
public static void deallocate(byte[] buff) {
    //缓冲池已达上限
    if (buffers.size() >= BUFFER_MAX_NUM) return;
    //回收的缓冲大小必须正确
    if (buff.length != BUFFER_SIZE) return;

    //加回到池中
    buffers.add(buff);
}
}

Anyway, I didn't tested the performance influenced by the reduction of buffer size and nums。maybe there is another good way to make it runner better on Android.

Your code is Excellent !

How to visite https url with sockslib?

this method works fine when the url contains http,
but it wouldn't works when the url contains https.
for example:
works fine: getResponse(new URL("http://www.worldjournal.com/"));
don't work: getResponse(new URL("https://google.com/"));
public static String getResponse(URL url){
String result = "";
StringBuilder builder = null;
InputStream inputStream = null;
OutputStream outputStream = null;
Socket socket = null;
int length = 0;
byte[] buffer = new byte[1024];
try {
SocksProxy proxy = new Socks5("x.x.x.x", 1080, new
UsernamePasswordCredentials("x", "x"));
socket = new SocksSocket(proxy, new InetSocketAddress(url.getHost(), url.getPort()));
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
printWriter.print("GET " + url + " HTTP/1.1\r\n");
printWriter.print("Host: " + url.getHost() + "\r\n");
printWriter.print("\r\n");
printWriter.flush();

        builder = new StringBuilder("");
        
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;
        
        while ((length = inputStream.read(buffer)) > 0) {
            System.out.print(new String(buffer, 0, length));
            builder.append(new String(buffer, 0, length));
        }

        inputStream.close();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return builder.toString();
}

ArrayIndexOutOfBoundfsException: -1

While trying the socks server using this project and opening in web browser websites seznam.cz and google.com with some search I received:

2018-06-17 14:54:36.526  INFO 3825 --- [      fs-thread] sockslib.server.BasicSocksProxyServer    : Start proxy server at port:1080
[WARNING] 
java.lang.ArrayIndexOutOfBoundsException: -1
        at java.util.ArrayList.fastRemove(ArrayList.java:550)
        at java.util.ArrayList.remove(ArrayList.java:533)
        at sockslib.server.io.StreamPipe.removePipeListener(StreamPipe.java:224)
        at sockslib.server.io.SocketPipe.close(SocketPipe.java:124)
        at sockslib.server.io.SocketPipe$PipeListenerImp.onStop(SocketPipe.java:208)
        at sockslib.server.io.StreamPipe.stop(StreamPipe.java:141)
        at sockslib.server.io.StreamPipe.run(StreamPipe.java:154)
        at java.lang.Thread.run(Thread.java:748)

Should I enable trace logger level to get more info?

Thx for response

Create proxy

Hello,
i have a problem with SOCKS5 socket.
"[12.06 00:38:13] javaw.exe *64 - domain.com error : Could not connect through proxy 127.0.0.1:8082 - Proxy server cannot establish a connection with the target - general SOCKS server failure."
@fengyouchao
code
SocksProxyServer proxyServer = SocksServerBuilder.buildAnonymousSocks5Server(8082); proxyServer.start();

And how i can listen everythink/connection etc on that socks like in esocks ?

Thank you

Support for turning off proxy when making connections to target server

Hi,
I'm using latest beta release of fucksocks in JUnit test and starting/stopping the server for each test. I'm configuring the proxy using Java system properties, however this prevents the socks proxy from working, since it attempts to connect to itself when making connection to destination server (Socks5Handler.doConnect(..)).
I have been able to workaround this by providing my own implementation of Socks5Handler which turns off proxy usage in doConnect:

socket = new Socket(Proxy.NO_PROXY);
socket.connect(new InetSocketAddress(commandMessage.getInetAddress(), commandMessage.getPort()));

I saw that in latest code there is an option to specify a socks proxy when making connection to destination server, but it does not look like it is possible to turn off proxy usage, do you think that adding such support makes sense?

By the way, are there any plans to release a new sockslib version anytime soon.

Thanks,
Detelin

SSL-related tests fail on JDK 11

Tests that make SSL connections fail due to errors when building with JDK 11. Specifically, these tests exhibit errors:

testConnectNoAuthSSLServer(sockslib.test.client.TestSSLSocks5): Connection reset
testConnectSSLAuthServer(sockslib.test.client.TestSSLSocks5): Connection reset
testSSLConnect(sockslib.test.quickstart.TestSocks5Server): Connection reset
testSSL2Connect(sockslib.test.quickstart.TestSocks5Server): Connection reset
tesSslUDP(sockslib.test.quickstart.TestSocks5Server): Received fatal alert: handshake_failure

This can be reproduced by building in containers. The tests pass when, in a local cloned repository directory, you execute

$ docker run -it --rm -v $PWD:/usr/src/sockslib -w /usr/src/sockslib maven:3.6-jdk-8 mvn clean install

...which builds with JDK 8, but they fail if you execute

$ docker run -it --rm -v $PWD:/usr/src/sockslib -w /usr/src/sockslib maven:3.6-jdk-11 mvn clean install

...which builds with JDK 11.

Partial build log showing the failures on JDK 11 is attached:
sockslib-build-jdk-11.log

Java version details are:

openjdk version "11.0.4" 2019-07-16
OpenJDK Runtime Environment 18.9 (build 11.0.4+11)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.4+11, mixed mode)

A workaround is to set the system property jdk.tls.client.protocols=TLSv1.2 as mentioned here. (This was revealed to me in a comment on this question.) That is, change the Maven command to

$ mvn clean install -Djdk.tls.client.protocols=TLSv1.2

However, because it seems that JDK 11 is defaulting to TLSv1.3, some change to the SSLConfiguration.getSSLSocketFactory() method is probably approprate. I do not know what that change is, though.

NullpointerException in CommandMessage

In some rare cases, getBytes() is null triggering this. I haven't looked at the details of when this happens exactly.

java.lang.NullPointerException: null
at sockslib.server.msg.CommandMessage.getBytes(CommandMessage.java:142) 
at sockslib.server.msg.CommandMessage.getLength(CommandMessage.java:104) 
at sockslib.server.SocksSession.read(SocksSession.java:115) 
at sockslib.server.Socks5Handler.handle(Socks5Handler.java:99) 
at sockslib.server.Socks5Handler.run(Socks5Handler.java:270) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) 
at java.lang.Thread.run(Thread.java:748)```

Out of Memory...

Hi , getting this when connecting to the device, Samsung Galaxy S9 Plus, any clue what's happening ?
Running as ForeGroundService , which launches & opens the port, but still can't make use of it...
Any help would be appreciated.

Screen Shot 2021-01-25 at 9 19 45 PM

Please add proper docs

It would be amazing if you add some great java docs & just a proper wiki on how to use the library with java
Because right now I had to check the src of esocks but it is outdated because it is based on fucksocks(before it was renamed to sockslib) & I couldn't find a better socks library to implement a socks5 proxy server with java

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.