java proxy 转包

2023-11-09

java proxy 转包

package org.rx.socks.proxy;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.rx.common.Logger;

import java.util.function.BiConsumer;

import static org.rx.common.Contract.require;

public class DirectClientHandler extends SimpleChannelInboundHandler<byte[]> {
    private BiConsumer<ChannelHandlerContext, byte[]> onReceive;
    private ChannelHandlerContext                     ctx;

    public Channel getChannel() {
        require(ctx);
        return ctx.channel();
    }

    public DirectClientHandler(BiConsumer<ChannelHandlerContext, byte[]> onReceive) {
        require(onReceive);

        this.onReceive = onReceive;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        this.ctx = ctx;
        Logger.info("DirectClientHandler %s connect %s", ctx.channel().localAddress(), ctx.channel().remoteAddress());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, byte[] bytes) {
        onReceive.accept(ctx, bytes);
        Logger.info("DirectClientHandler %s recv %s bytes from %s", ctx.channel().remoteAddress(), bytes.length,
                ctx.channel().localAddress());
    }

    public ChannelFuture send(byte[] bytes) {
        try {
            return ctx.channel().writeAndFlush(bytes);
        } finally {
            Logger.info("DirectClientHandler %s send %s bytes to %s", ctx.channel().localAddress(), bytes.length,
                    ctx.channel().remoteAddress());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        Logger.error(cause, "DirectClientHandler");
        ctx.close();
    }
}
package org.rx.socks.proxy;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.rx.common.Logger;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;

import static org.rx.common.Contract.require;

public class DirectServerHandler extends SimpleChannelInboundHandler<byte[]> {
    private static class ClientState {
        private ProxyClient directClient;
        //        private int                         length;
        //        private MemoryStream                stream;

        public ProxyClient getDirectClient() {
            return directClient;
        }

        public ClientState(boolean enableSsl, SocketAddress directAddress,
                           BiConsumer<ChannelHandlerContext, byte[]> onReceive) {
            require(directAddress, onReceive);

            directClient = new ProxyClient();
            directClient.setEnableSsl(enableSsl);
            directClient.connect((InetSocketAddress) directAddress, onReceive);
            //            stream = new MemoryStream(32, true);
        }

        //        private int readRemoteAddress(byte[] bytes) {
        //            int offset = 0;
        //            if (length == -1) {
        //                stream.setLength(length = Bytes.toInt(bytes, 0));
        //                stream.setPosition(0);
        //                offset = Integer.BYTES;
        //            }
        //            int count = length - stream.getPosition();
        //            stream.write(bytes, offset, Math.min(count, bytes.length));
        //            if (stream.getPosition() < length) {
        //                return -1;
        //            }
        //
        //            directAddress = Sockets.parseAddress(Bytes.toString(stream.getBuffer(), 0, length));
        //            length = -1;
        //            return bytes.length - count;
        //        }
    }

    private final Map<ChannelHandlerContext, ClientState> clients;
    private boolean                                       enableSsl;
    private SocketAddress                                 directAddress;

    public DirectServerHandler(boolean enableSsl, SocketAddress directAddress) {
        require(directAddress);

        clients = new ConcurrentHashMap<>();
        this.enableSsl = enableSsl;
        this.directAddress = directAddress;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        clients.put(ctx, new ClientState(enableSsl, directAddress, (directChannel, bytes) -> {
            ctx.writeAndFlush(bytes);
            Logger.info("DirectServerHandler %s recv %s bytes from %s", ctx.channel().remoteAddress(), bytes.length,
                    directAddress);
        }));
        Logger.info("DirectServerHandler %s connect %s", ctx.channel().remoteAddress(), directAddress);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, byte[] bytes) {
        ClientState state = clients.get(ctx);
        require(state);

        ProxyClient directClient = state.getDirectClient();
        directClient.send(bytes);
        Logger.info("DirectServerHandler %s send %s bytes to %s",
                directClient.getHandler().getChannel().remoteAddress(), bytes.length, ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        clients.remove(ctx);
        Logger.info("DirectServerHandler %s disconnect %s", ctx.channel().remoteAddress(), directAddress);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        Logger.error(cause, "DirectServerHandler");
        ctx.close();
    }
}
package org.rx.socks.proxy;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.compression.ZlibCodecFactory;
import io.netty.handler.codec.compression.ZlibWrapper;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import lombok.SneakyThrows;
import org.rx.common.App;
import org.rx.common.Disposable;

import java.net.InetSocketAddress;
import java.util.function.BiConsumer;

import static org.rx.common.Contract.require;
import static org.rx.socks.proxy.ProxyServer.Compression_Key;

public class ProxyClient extends Disposable {
    private EventLoopGroup      group;
    private boolean             enableSsl;
    private DirectClientHandler handler;

    public boolean isEnableSsl() {
        return enableSsl;
    }

    public void setEnableSsl(boolean enableSsl) {
        this.enableSsl = enableSsl;
    }

    public boolean isEnableCompression() {
        return App.convert(App.readSetting(Compression_Key), boolean.class);
    }

    public DirectClientHandler getHandler() {
        checkNotClosed();
        return handler;
    }

    @Override
    protected void freeObjects() {
        if (group != null) {
            group.shutdownGracefully();
        }
    }

    public void connect(InetSocketAddress remoteAddress) {
        connect(remoteAddress, null);
    }

    @SneakyThrows
    public void connect(InetSocketAddress remoteAddress, BiConsumer<ChannelHandlerContext, byte[]> onReceive) {
        checkNotClosed();
        require(group == null);
        require(remoteAddress);

        // Configure SSL.
        SslContext sslCtx = null;
        if (enableSsl) {
            sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        }

        Bootstrap b = new Bootstrap();
        SslContext ssl = sslCtx;
        b.group(group = new NioEventLoopGroup()).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        if (ssl != null) {
                            pipeline.addLast(
                                    ssl.newHandler(ch.alloc(), remoteAddress.getHostName(), remoteAddress.getPort()));
                        }
                        if (isEnableCompression()) {
                            pipeline.addLast(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP));
                            pipeline.addLast(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP));
                        }

                        pipeline.addLast(new ByteArrayDecoder());
                        pipeline.addLast(new ByteArrayEncoder());

                        pipeline.addLast(new DirectClientHandler(onReceive));
                    }
                });
        ChannelFuture f = b.connect(remoteAddress).sync();
        handler = (DirectClientHandler) f.channel().pipeline().last();
    }

    public ChannelFuture send(byte[] bytes) {
        checkNotClosed();
        require(group != null);
        require(bytes);

        return getHandler().send(bytes);
    }
}
package org.rx.socks.proxy;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.compression.ZlibCodecFactory;
import io.netty.handler.codec.compression.ZlibWrapper;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import lombok.SneakyThrows;
import org.rx.common.App;
import org.rx.common.Disposable;
import org.rx.socks.Sockets;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

import static org.rx.common.Contract.require;

public final class ProxyServer extends Disposable {
    public static final String Compression_Key = "app.netProxy.compression";
    public static final String ListenBlock_Key = "app.netProxy.listenBlock";
    private EventLoopGroup     group;
    private boolean            enableSsl;

    public boolean isEnableSsl() {
        return enableSsl;
    }

    public void setEnableSsl(boolean enableSsl) {
        this.enableSsl = enableSsl;
    }

    public boolean isEnableCompression() {
        return App.convert(App.readSetting(Compression_Key), boolean.class);
    }

    public boolean isListening() {
        return group != null;
    }

    private boolean isListenBlock() {
        return App.convert(App.readSetting(ListenBlock_Key), boolean.class);
    }

    @Override
    protected void freeObjects() {
        if (group != null) {
            group.shutdownGracefully();
        }
    }

    public void start(int localPort, SocketAddress directAddress) {
        start(new InetSocketAddress(Sockets.AnyAddress, localPort), directAddress);
    }

    @SneakyThrows
    public void start(SocketAddress localAddress, SocketAddress directAddress) {
        checkNotClosed();
        require(group == null);
        require(localAddress);

        // Configure SSL.
        SslContext sslCtx = null;
        if (enableSsl) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        }

        ServerBootstrap b = new ServerBootstrap();
        SslContext ssl = sslCtx;
        b.group(group = new NioEventLoopGroup()).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        if (ssl != null) {
                            pipeline.addLast(ssl.newHandler(ch.alloc()));
                        }
                        if (isEnableCompression()) {
                            // Enable stream compression (you can remove these two if unnecessary)
                            pipeline.addLast(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP));
                            pipeline.addLast(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP));
                        }

                        // Add the number codec first,
                        pipeline.addLast(new ByteArrayDecoder());
                        pipeline.addLast(new ByteArrayEncoder());

                        // and then business logic.
                        // Please note we create a handler for every new channel because it has stateful properties.
                        pipeline.addLast(new DirectServerHandler(enableSsl, directAddress));
                    }
                });
        ChannelFuture f = b.bind(localAddress).sync();
        if (isListenBlock()) {
            f.channel().closeFuture().sync();
        }
    }

    public void closeClients() {
        checkNotClosed();
        if (group == null) {
            return;
        }

        group.shutdownGracefully();
        group = null;
    }
}

 

posted on 2019-02-02 10:58 RockyLOMO 阅读(...) 评论(...) 编辑 收藏

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

java proxy 转包 的相关文章

随机推荐

  • C# NPOI 设置(.xlsx) 【单元格填充】以及【字体颜色】

    C NPOI 设置 xlsx 单元格填充 以及 字体颜色 写在前面 因为我需要用到NPOI处理 xlsx文件 需要设置单元格填充及字体颜色 期间网上搜索的时候很麻烦 结果五花八门 提炼一下 记录在此 引用 using NPOI XSSF U
  • XSS绕过技巧总结

    XSS绕过技巧 作者 白泽Sec安全实验室 前言 XSS是Web应用程序中常见的漏洞之一 网站管理员可以通过用户输入过滤 根据上下文转换输出数据 正确使用DOM 强制执行跨源资源共享 CORS 策略以及其他的安全策略来规避XSS漏洞 尽管现
  • 一个重构:开闭原则案例

    原始代码 public class Alert private AlertRule rule private Notification notification public Alert AlertRule rule Notificatio
  • QT TCP socket通信(二)

    在上一节里我们使用TCP服务器发送一个字符串 然后在TCP客户端进行接收 在这一节我们重新写一个客户端程序和一个服务器程序 这次我们让客户端进行文件的发送 服务器进行文件的接收 有了上一节的基础 这一节的内容就很好理解了 注意一下几个信号和
  • Unity问题合集

    目录 1 监听事件居然有顺序 2 StopCoroutine并不能停止协程 3 实例化instance的脚本需要挂载到场景中的物体中 不然无法调取 4 GetComponentsInChildren获取不到隐藏物体 5 Animator窗口
  • CVE-2017-11882---Microsoft Office数学公式编辑器内存损坏漏洞

    做过不少ctf中的pwn 但还是头一次复现windows的溢出漏洞 目的有二 第一 学会使用windbg 了解它的适用情况和优势 第二 体验在windows下调试溢出漏洞 看看和linux下调试有何不同 0x01 漏洞背景 2017 11
  • Python处理大数据,如何提高处理速度

    Python处理大数据 如何提高处理速度 一 利用大数据分析工具 Dask https dask org Dask简介 Dask支持Pandas的DataFrame和NumpyArray的数据结构 并且既可在本地计算机上运行 也可以扩展到在
  • 《逻辑与计算机设计基础(原书第5版)》——2.10 硬件描述语言—Verilog

    2 10 硬件描述语言 Verilog 由于硬件描述语言用来描述和设计硬件 故在使用该语言编程时 应牢记底层的硬件实现 特别是当你的设计将用来综合时 例如 如果忽略将要生成的硬件 那么你可能会用低效的硬件描述语言设计出一个大且复杂的门级结构
  • Qt小例子学习53 - 使用resizeEvent调整窗口大小时调整Qlabel的图像大小

    Qt小例子学习53 使用resizeEvent调整窗口大小时调整Qlabel的图像大小 testsize h ifndef TESTSIZE H define TESTSIZE H include
  • Qt6+vtk9入门

    目录 1 Qt下载 2 Qt Creator手册 1 edit toolbar 2 双击某控件更改控件名称 3 Qt signal slot Qt 6 vtk9 1 vs2019配置 1 Qt下载 现在下载Qt需要先注册Qt账号 地址htt
  • 【机器学习之向量求导】分子布局 分母布局

    请思考 维度为m的一个向量 对一个标量 的求导 那么结果也是一个m维的向量 这个m维的求导结果排列成的m维向量到底应该是列向量还是行向量 这个问题的答案是 行向量或者列向量皆可 毕竟我们求导的本质只是把标量求导的结果排列起来 至于是按行排列
  • 2016物联网版图:物联网奇点是否已经来临?

    物联网是世界上最让人觉得疑惑的科技趋势吗 一方面 我们了解到它将要成为史诗般的存在 并且所有的预言都说它将带来数百亿互联的设备 创造多达万亿美元的经济价值 但是 在另外一方面 终端用户呈现出的主要感觉是 无聊 现在的IoT感觉就是新互联产品
  • linux之间文件传输(转)

    linux的scp命令 linux 的 scp 命令 可以 在 linux 之间复制 文件 和 目录 scp 命令 scp 可以在 2个 linux 主机间复制文件 命令基本格式 scp 可选参数 file source file targ
  • linux下mysql创建数据库注意

    1 create database a b 为Esc键下面那个键
  • 接口测试用例设计

    接口测试用例设计一 1 接口测试概念 接口测试 测试系统间接口的一种测试 测试的对象主要是接口 主要是测试外部系统与所测系统之间以及内部系统之间的交互点 2 接口测试方法 a 可以通过开发脚本代码进行测试 b 可以通过开源免费的接口调用调试
  • ViewPager2 + Fragment(同一个Fragment)ToolBar显示异常

    一个需求 实现Viewpager2 Fragment实现数据的展示 Viewpager外层不是Activity 而是Fragment 详细说明 在一个Viewpager下 使用的是同一个Fragment 由于每一个Fragment显示的数据
  • 数据结构 —— 顺序表的结构、功能(增删查改)。

    一 概念及结构 顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构 一般情况下采用数据存储 在数组上完成数据的增删查改 顺序表的数据必须从第一个位置开始 连续存储的 顺序表一般可以分为 1 1 静态顺序表 使用定长数组存储元素
  • 苹果笔记本学计算机二级方便吗,你是否真的需要MacBook?

    你们好 这里是Sweekli 为你寻找苹果最新资讯 苹果隐藏技巧 苹果良心APP以及苹果优质配件 如果你需要这些 不妨点个关注 目前 主流的电脑操作系统可能有Windows Mac OS Linux和Chrome OS等 但普通用户在选购时
  • Java的前景如何,好不好自学?

    作为一名拥有十年编程经验的老鸟 我觉得还是很有资格来回答这个问题的 毕竟刚下飞机 首先来回答 Java 的前景如何 在我眼里 Java 绝对是世界第一编程语言啊 PHP 表示不服 那也没办法啊 来看 TIOBE 这个编程语言排行榜吧 上面这
  • java proxy 转包

    java proxy 转包 package org rx socks proxy import io netty channel Channel import io netty channel ChannelFuture import io