Compare commits

...
23 Commits
Author SHA1 Message Date
傲世孤尘 5f2d67937d !45 更新测试报告
Merge pull request !45 from NichenFly/dev
2023-11-16 11:53:57 +00:00
= 45f9756b68 去掉一些日志输出 2023-11-16 10:52:11 +08:00
az 0548a9b13e 更新不加密、SM2+AES加密方式的性能对比报告 2023-11-15 20:35:46 +08:00
傲世孤尘 6c2873e453 !44 添加SM2+AES加密与SSL加密的测试报告
Merge pull request !44 from NichenFly/dev
2023-11-15 07:09:44 +00:00
= de243149a9 报告中添加测试代码 2023-11-15 14:57:40 +08:00
= dfb22fa148 添加SM2+AES、SSL的测试内容 2023-11-15 14:53:58 +08:00
= 3b77ecddb9 取消使用hutool的工具进行sm2和aes的加解密 2023-11-15 12:11:22 +08:00
傲世孤尘 5b7962d727 !43 添加配置项sm2-encrypt-enable
Merge pull request !43 from NichenFly/dev
2023-11-15 01:55:49 +00:00
az 9c5ad7aa72 添加配置项目,修改日志信息,不输出公钥信息 2023-11-14 22:04:00 +08:00
傲世孤尘 c7c58a806d !42 解决加密链路解码异常问题
Merge pull request !42 from NichenFly/dev
2023-11-14 13:38:17 +00:00
az 8c14727fba 修复加密过程中的通道编码异常问题 2023-11-14 21:31:08 +08:00
= f2005b3e74 修改参数 2023-11-14 17:04:10 +08:00
= 4569165993 加密算法改为AES 2023-11-10 16:37:30 +08:00
= fc1ba4eb1a Encoder执行完后进行空间释放 2023-11-09 09:00:52 +08:00
傲世孤尘 5a7ac41911 !41 解决加密链路解码异常问题
Merge pull request !41 from NichenFly/dev
2023-11-08 13:23:13 +00:00
az 6c6506c677 解决加密链路解码异常问题 2023-11-08 21:19:29 +08:00
傲世孤尘 4afd300c92 !40 链路使用国密算法对链路进行加密,保证传输过程中信息的机密性
Merge pull request !40 from NichenFly/dev
2023-11-08 06:40:50 +00:00
= 55f85861cf 添加输出信息 2023-11-08 14:08:42 +08:00
= 1698e944ee 修改运行参数 2023-11-08 09:31:39 +08:00
az 8842ae2899 添加非安全判断 2023-11-07 22:33:39 +08:00
= 4eb04e6f0f 修改encoder和decoder适配加密过程 2023-11-07 16:46:18 +08:00
= a16fba4b03 密码协商过程 2023-11-07 15:25:41 +08:00
= 726f38c332 添加SM2、SM4的生成密钥和加解密方法 2023-11-07 10:43:26 +08:00
27 changed files with 911 additions and 46 deletions
@@ -0,0 +1,88 @@
# 客户端与服务器端采用不加密、SM2+AES加密、SSL加密方式进行的性能测试比较
* 本测试不作为性能测试参考,仅作为三种数据加密方式的性能比较使用
* 本测试使用的操作系统为windows10,
* 本测试使用的测试环境配置:内存:16G,CPU:i716核
## 1、测试程序准备情况
* 将程序分别打包为`server``client``jar`包,在本地运行一个`server`
* 拷贝三个客户端配置文件,配置文件名称为`app.yml``app-sm2-aes.yml``app-ssl.yml`,并修改相应配置,适配不加密、SM2+AES加密和SSL加密
## 2、测试思路和实现
1)准备1KB、10KB、20KB、50KB、100KB、1MB、2MB、5MB、10MB、20MB、100MB、500MB的文件
2)使用Nodejs实现的anywhere工具,在本地运行简单http服务
3)在server端生成3个licenseKey,分别对应不加密、SM2+AES加密和SSL加密通道,端口分别为9101,9102和9103,并同时映射到anywhere的8000端口
4)使用Hutool里的HttpUtil工具包,对每个文件进行下载,记录下载使用时间,重复执行10次
## 3、测试结果
序号| 加密方式 | 文件大小 |响应时间(ms)
---|---|---|---
1| 不加密 | 1KB |4
2| SM2+AES | 1KB |21
3| SSL | 1KB |67
4| 不加密 | 10KB |3
5| SM2+AES | 10KB |7
6| SSL | 10KB |4
7| 不加密 | 20KB |4
8| SM2+AES | 20KB |6
9| SSL | 20KB |5
10| 不加密 | 50KB |4
11| SM2+AES | 50KB |7
12| SSL | 50KB |6
13| 不加密 | 100KB |6
14| SM2+AES | 100KB |8
15| SSL | 100KB |6
16| 不加密 | 1MB |19
17| SM2+AES | 1MB |30
18| SSL | 1MB |19
19| 不加密 | 2MB |21
20| SM2+AES | 2MB |40
21| SSL | 2MB |24
22| 不加密 | 5MB |31
23| SM2+AES | 5MB |51
24| SSL | 5MB |36
25| 不加密 | 10MB |44
26| SM2+AES | 10MB |85
27| SSL | 10MB |47
28| 不加密 | 20MB |63
29| SM2+AES | 20MB |139
30| SSL | 20MB |92
31| 不加密 | 100MB |323
32| SM2+AES | 100MB |590
33| SSL | 100MB |322
34| 不加密 | 500MB |1414
35| SM2+AES | 500MB |2797
36| SSL | 500MB |1561
## 4、测试结论
从测试结果可以看出,SSL加密的方式在大部分情况下比SM2+AES的加密方式效率高。
## 5、测试使用的代码
```java
public static void main(String[] args) {
int serialNumber = 1;
int[] ports = new int[]{9101, 9102, 9103};
Map<Integer, String> portMap = new HashMap<>();
portMap.put(9101, "不加密");
portMap.put(9102, "SM2+AES");
portMap.put(9103, "SSL");
HttpUtil.downloadBytes("http://127.0.0.1:9101/1KB"); // 使用不加密通道做一下测试,避免初始化时耗时过高
String[] fileNames = "1KB,10KB,20KB,50KB,100KB,1MB,2MB,5MB,10MB,20MB,100MB,500MB".split(",");
for (String fileName : fileNames) {
for (int port : ports) {
String url = String.format("http://127.0.0.1:%s/%s", port, fileName);
long startTime = System.currentTimeMillis();
HttpUtil.downloadBytes(url);
long endTime = System.currentTimeMillis();
long resTimeMs = endTime - startTime;
String record = String.format("%s|%s|%s|%s", serialNumber++, portMap.get(port), fileName, resTimeMs);
System.out.println(record);
}
}
}
```
+1 -1
View File
@@ -1,5 +1,5 @@
module.exports = {
NODE_ENV: '"production"',
ENV_CONFIG: '"prod"',
BASE_API: '"https://api-prod"'
BASE_API: '""'
}
+1 -1
View File
@@ -70,7 +70,7 @@
"friendly-errors-webpack-plugin": "1.6.1",
"html-webpack-plugin": "2.30.1",
"node-notifier": "5.1.2",
"node-sass": "^4.7.2",
"node-sass": "^9.0.0",
"optimize-css-assets-webpack-plugin": "3.2.0",
"ora": "1.3.0",
"portfinder": "1.0.13",
@@ -24,6 +24,7 @@ public class ProxyClient {
setAlias("neutrino.proxy.tunnel.server-ip", "serverIp");
setAlias("neutrino.proxy.tunnel.server-port", "serverPort");
setAlias("neutrino.proxy.tunnel.sm2-encrypt-enable", "sm2EncryptEnable");
setAlias("neutrino.proxy.tunnel.ssl-enable", "sslEnable");
setAlias("neutrino.proxy.tunnel.jks-path", "jksPath");
setAlias("neutrino.proxy.tunnel.key-store-password", "keyStorePassword");
@@ -37,6 +37,7 @@ public class ProxyConfig {
private String jksPath;
private String serverIp;
private Integer serverPort;
private Boolean sm2EncryptEnable;
private Boolean sslEnable;
private Integer obtainLicenseInterval;
private String licenseKey;
@@ -1,6 +1,7 @@
package org.dromara.neutrinoproxy.client.handler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.client.config.ProxyConfig;
import org.dromara.neutrinoproxy.core.Constants;
@@ -8,6 +9,7 @@ import org.dromara.neutrinoproxy.core.ExceptionEnum;
import org.dromara.neutrinoproxy.core.ProxyMessage;
import org.dromara.neutrinoproxy.core.ProxyMessageHandler;
import org.dromara.neutrinoproxy.core.dispatcher.Match;
import org.dromara.neutrinoproxy.core.util.EncryptUtil;
import org.noear.snack.ONode;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Component;
@@ -29,7 +31,7 @@ public class ProxyMessageAuthHandler implements ProxyMessageHandler {
String info = proxyMessage.getInfo();
ONode load = ONode.load(info);
Integer code = load.get("code").getInt();
log.info("Auth result:{}", info);
log.info("Auth result: {}", load.get("msg").getString());
if (ExceptionEnum.AUTH_FAILED.getCode().equals(code)) {
// 客户端认证失败,直接停止服务
log.info("client auth failed , client stop.");
@@ -42,5 +44,26 @@ public class ProxyMessageAuthHandler implements ProxyMessageHandler {
){
context.channel().close();
}
// 是否进行通道加密
if (!proxyConfig.getTunnel().getSm2EncryptEnable()) {
return;
}
// 默认设置为非安全链路,需要服务端确认后,再设置为安全链路
Attribute<Boolean> booleanAttribute = context.attr(Constants.IS_SECURITY);
booleanAttribute.set(false);
// 获取认证成功的后的公钥信息,并生成随机密码,加密发到服务端确认
String publicKey = load.get("publicKey").getString();
byte[] secureKey = EncryptUtil.generateAesKey();
// 存储密码
Attribute<byte[]> secureKeyAttr = context.attr(Constants.SECURE_KEY);
secureKeyAttr.set(secureKey);
// 使用SM2算法对密钥进行加密并发送到服务端
byte[] encryptSecureKey = EncryptUtil.encryptBySm2(publicKey, secureKey);
context.writeAndFlush(ProxyMessage.buildSecureKeyMessage(encryptSecureKey));
context.flush();
}
}
@@ -56,12 +56,15 @@ public class ProxyMessageConnectHandler implements ProxyMessageHandler {
channel.attr(Constants.NEXT_CHANNEL).set(realServerChannel);
realServerChannel.attr(Constants.NEXT_CHANNEL).set(channel);
// 远程绑定
// 通知服务端进行远程绑定,此绑定信息不加密,该条消息为身份标识
channel.writeAndFlush(ProxyMessage.buildConnectMessage(visitorId + "@" + proxyConfig.getTunnel().getLicenseKey()));
realServerChannel.config().setOption(ChannelOption.AUTO_READ, true);
ProxyUtil.addRealServerChannel(visitorId, realServerChannel);
ProxyUtil.setRealServerChannelVisitorId(realServerChannel, visitorId);
// 连接信息发送后,将该通道设置为加密
ProxyUtil.setChannelSecurity(channel);
}
@Override
@@ -0,0 +1,49 @@
package org.dromara.neutrinoproxy.client.handler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.client.config.ProxyConfig;
import org.dromara.neutrinoproxy.client.util.ProxyUtil;
import org.dromara.neutrinoproxy.core.Constants;
import org.dromara.neutrinoproxy.core.ProxyMessage;
import org.dromara.neutrinoproxy.core.ProxyMessageHandler;
import org.dromara.neutrinoproxy.core.dispatcher.Match;
import org.dromara.neutrinoproxy.core.util.EncryptUtil;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
@Slf4j
@Match(type = Constants.ProxyDataTypeName.SECURE_KEY)
@Component
public class ProxyMessageSecureKeyHandler implements ProxyMessageHandler {
@Inject
private ProxyConfig proxyConfig;
@Override
public void handle(ChannelHandlerContext ctx, ProxyMessage proxyMessage) {
if (!proxyConfig.getTunnel().getSm2EncryptEnable()) {
return;
}
log.info("收到服务端的加密确认");
Attribute<byte[]> secureKeyAttr = ctx.attr(Constants.SECURE_KEY);
byte[] secureKey = secureKeyAttr.get();
byte[] data = proxyMessage.getData();
byte[] decryptedData = EncryptUtil.decryptByAes(secureKey, data);
String m = new String(decryptedData);
if ("ok".equals(m)) {
// 设置当前cmd通道为安全,之后使用该通道传输的消息均会加密
Attribute<Boolean> booleanAttribute = ctx.attr(Constants.IS_SECURITY);
booleanAttribute.set(true);
// 全局存储密钥
ProxyUtil.setSecureKey(secureKey);
log.info("Encrypted link established successfully");
} else {
ctx.channel().close();
}
}
}
@@ -46,6 +46,9 @@ public class UdpProxyMessageConnectHandler implements ProxyMessageHandler {
.setTargetIp(udpBaseInfo.getTargetIp())
.setTargetPort(udpBaseInfo.getTargetPort())
).setData(proxyConfig.getTunnel().getLicenseKey().getBytes()));
// connect类型的消息不加密,用于标识身份,发送标识消息后,再将通道设置加密标识
ProxyUtil.setChannelSecurity(channel);
}
@Override
@@ -72,6 +72,8 @@ public class ProxyUtil {
private static String clientId;
private static final String CLIENT_ID_FILE = ".NEUTRINO_PROXY_CLIENT_ID";
private static byte[] secureKey = null;
public static void borrowTcpProxyChanel(Bootstrap tcpProxyTunnelBootstrap, final ProxyChannelBorrowListener borrowListener) {
Channel channel = tcpProxyChannelPool.poll();
if (null != channel) {
@@ -89,6 +91,10 @@ public class ProxyUtil {
}
public static void returnTcpProxyChanel(Channel proxyChanel) {
if (proxyChanel != null) {
proxyChanel.attr(Constants.IS_SECURITY).set(null);
proxyChanel.attr(Constants.SECURE_KEY).set(null);
}
if (tcpProxyChannelPool.size() > MAX_POOL_SIZE) {
proxyChanel.close();
} else {
@@ -121,6 +127,10 @@ public class ProxyUtil {
}
public static void returnUdpProxyChanel(Channel proxyChanel) {
if (proxyChanel != null) {
proxyChanel.attr(Constants.IS_SECURITY).set(null);
proxyChanel.attr(Constants.SECURE_KEY).set(null);
}
if (udpProxyChannelPool.size() > MAX_POOL_SIZE) {
proxyChanel.close();
} else {
@@ -223,4 +233,16 @@ public class ProxyUtil {
return null;
}
public static void setSecureKey(byte[] key) {
secureKey = key;
}
public static void setChannelSecurity(Channel channel) {
if (null == secureKey) {
return;
}
channel.attr(Constants.IS_SECURITY).set(true);
channel.attr(Constants.SECURE_KEY).set(secureKey);
}
}
@@ -23,7 +23,7 @@ neutrino:
proxy:
protocol:
max-frame-length: 2097152
max-frame-length: 1048576000
length-field-offset: 0
length-field-length: 4
initial-bytes-to-strip: 0
@@ -34,17 +34,18 @@ neutrino:
tunnel:
# 线程池相关配置,用于技术调优,可忽略
thread-count: 50
sm2-encrypt-enable: ${SM2_ENCRYPT_ENABLE:true}
# 隧道SSL证书配置
key-store-password: ${STORE_PASS:123456}
jks-path: ${JKS_PATH:classpath:/test.jks}
# 服务端IP
server-ip: ${SERVER_IP:localhost}
# 服务端端口(对应服务端app.yml中的tunnel.port、tunnel.ssl-port)
server-port: ${SERVER_PORT:9002}
server-port: ${SERVER_PORT:9000}
# 是否启用SSL(注意:该配置必须和server-port对应上)
ssl-enable: ${SSL_ENABLE:true}
ssl-enable: ${SSL_ENABLE:false}
# 客户端连接唯一凭证
license-key: ${LICENSE_KEY:}
license-key: ${LICENSE_KEY:b0a907332b474b25897c4dcb31fc7eb6}
# 客户端唯一身份标识(可忽略,若不设置首次启动会自动生成)
client-id: ${CLIENT_ID:}
# 是否开启隧道传输报文日志(日志级别为debug时开启才有效)
+11
View File
@@ -24,12 +24,23 @@
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15to18</artifactId>
</dependency>
<!--hutool -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>${hutool.version}</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-crypto</artifactId>
<version>${hutool.version}</version>
</dependency>
</dependencies>
<build>
@@ -38,6 +38,12 @@ public interface Constants {
AttributeKey<String> VISITOR_ID = AttributeKey.newInstance("visitor_id");
AttributeKey<String> SECURE_PRIVATE_KEY = AttributeKey.newInstance("secure_private_key");
AttributeKey<byte[]> SECURE_KEY = AttributeKey.newInstance("secure_key");
AttributeKey<Boolean> IS_SECURITY = AttributeKey.newInstance("is_security");
AttributeKey<Integer> LICENSE_ID = AttributeKey.newInstance("license_id");
AttributeKey<String> TARGET_IP = AttributeKey.newInstance("targetIp");
@@ -57,6 +63,7 @@ public interface Constants {
interface ProxyDataTypeName {
String HEARTBEAT = "HEARTBEAT";
String SECURE_KEY = "SECURE_KEY";
String AUTH = "AUTH";
String CONNECT = "CONNECT";
String DISCONNECT = "DISCONNECT";
@@ -0,0 +1,31 @@
/**
* Copyright (c) 2022 aoshiguchen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.dromara.neutrinoproxy.core;
/**
* 存储公钥和私钥
* @param privateKey
* @param publicKey
*/
public record KeyPairRecord(String privateKey, String publicKey) {
}
@@ -47,7 +47,9 @@ public enum ProxyDataTypeEnum {
PORT_MAPPING_SYNC(0x07, Constants.ProxyDataTypeName.PORT_MAPPING_SYNC, "PORT_MAPPING_SYNC"),
UDP_CONNECT(0x08, Constants.ProxyDataTypeName.UDP_CONNECT,"UDP_CONNECT"),
UDP_DISCONNECT(0x09, Constants.ProxyDataTypeName.UDP_DISCONNECT,"UDP_DISCONNECT"),
UDP_TRANSFER(0x10, Constants.ProxyDataTypeName.UDP_TRANSFER,"UDP_TRANSFER");
UDP_TRANSFER(0x10, Constants.ProxyDataTypeName.UDP_TRANSFER,"UDP_TRANSFER"),
SECURE_KEY(0x11, Constants.ProxyDataTypeName.SECURE_KEY, "SECURE_KEY"),
;
private static Map<Integer,ProxyDataTypeEnum> cache = Stream.of(values()).collect(Collectors.toMap(ProxyDataTypeEnum::getType, Function.identity()));
private int type;
@@ -24,6 +24,7 @@ package org.dromara.neutrinoproxy.core;
import lombok.Data;
import lombok.experimental.Accessors;
import org.dromara.neutrinoproxy.core.util.EncryptUtil;
import org.noear.snack.ONode;
import java.util.Arrays;
@@ -79,6 +80,11 @@ public class ProxyMessage {
*/
public static final byte TYPE_UDP_TRANSFER = 0x10;
/**
* 安全密钥协商
*/
public static final byte TYPE_SECURE_KEY = 0x11;
/**
* 消息类型
*/
@@ -117,11 +123,12 @@ public class ProxyMessage {
.setInfo(info + "," + clientId);
}
public static ProxyMessage buildAuthResultMessage(Integer code, String msg, String licenseKey) {
public static ProxyMessage buildAuthResultMessage(Integer code, String msg, String licenseKey, String publicKey) {
ONode data = ONode.newObject();
data.set("code", code);
data.set("msg", msg);
data.set("licenseKey", licenseKey);
data.set("publicKey", publicKey);
return create().setType(TYPE_AUTH)
.setInfo(data.toJson());
}
@@ -136,6 +143,17 @@ public class ProxyMessage {
.setInfo(info);
}
public static ProxyMessage buildSecureKeyMessage(byte[] secureKey) {
return create().setType(TYPE_SECURE_KEY)
.setInfo(EncryptUtil.digestBySm3(secureKey))
.setData(secureKey);
}
public static ProxyMessage buildSecureKeyReturnMessage(byte[] content) {
return create().setType(TYPE_SECURE_KEY)
.setData(content);
}
public static ProxyMessage buildTransferMessage(String visitorId, byte[] data) {
return create().setType(TYPE_TRANSFER)
.setInfo(visitorId)
@@ -22,11 +22,18 @@
package org.dromara.neutrinoproxy.core;
import cn.hutool.core.util.HexUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.util.Attribute;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.core.util.EncryptUtil;
import static org.dromara.neutrinoproxy.core.Constants.*;
@Slf4j
/**
*
* @author: aoshiguchen
@@ -70,28 +77,52 @@ public class ProxyMessageDecoder extends LengthFieldBasedFrameDecoder {
return null;
}
int frameLength = in.readInt();
if (in.readableBytes() < frameLength) {
return null;
Attribute<Boolean> booleanAttribute = ctx.attr(Constants.IS_SECURITY);
Boolean isSecurity = booleanAttribute.get();
ByteBuf buf;
// 考虑isSecurity为null的情况,null的情况也为false
if (isSecurity != null && isSecurity) {
int packageLength = in.readInt();
if (in.readableBytes() < packageLength) {
return null;
}
// 获取加密数据
byte[] encryptedBytes = new byte[packageLength];
in.readBytes(encryptedBytes);
in.release();
// 获取解密密钥
Attribute<byte[]> secureKeyAttr = ctx.attr(SECURE_KEY);
byte[] secureKey = secureKeyAttr.get();
// 解密
byte[] decryptedData = EncryptUtil.decryptByAes(secureKey, encryptedBytes);
buf = Unpooled.wrappedBuffer(decryptedData);
} else {
buf = in;
}
ProxyMessage proxyMessage = new ProxyMessage();
byte type = in.readByte();
long sn = in.readLong();
int frameLength = buf.readInt();
byte type = buf.readByte();
long sn = buf.readLong();
proxyMessage.setSerialNumber(sn);
proxyMessage.setType(type);
int infoLength = in.readInt();
int infoLength = buf.readInt();
byte[] infoBytes = new byte[infoLength];
in.readBytes(infoBytes);
buf.readBytes(infoBytes);
proxyMessage.setInfo(new String(infoBytes));
byte[] data = new byte[frameLength - TYPE_SIZE - SERIAL_NUMBER_SIZE - INFO_LENGTH_SIZE - infoLength];
in.readBytes(data);
buf.readBytes(data);
proxyMessage.setData(data);
in.release();
buf.release();
return proxyMessage;
}
@@ -22,9 +22,15 @@
package org.dromara.neutrinoproxy.core;
import cn.hutool.core.util.HexUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.Attribute;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.core.util.EncryptUtil;
import static org.dromara.neutrinoproxy.core.Constants.*;
/**
@@ -32,6 +38,7 @@ import static org.dromara.neutrinoproxy.core.Constants.*;
* @author: aoshiguchen
* @date: 2022/6/16
*/
@Slf4j
public class ProxyMessageEncoder extends MessageToByteEncoder<ProxyMessage> {
public ProxyMessageEncoder() {
@@ -40,6 +47,7 @@ public class ProxyMessageEncoder extends MessageToByteEncoder<ProxyMessage> {
@Override
protected void encode(ChannelHandlerContext ctx, ProxyMessage msg, ByteBuf out) throws Exception {
int bodyLength = TYPE_SIZE + SERIAL_NUMBER_SIZE + INFO_LENGTH_SIZE;
byte[] infoBytes = null;
if (msg.getInfo() != null) {
@@ -51,21 +59,50 @@ public class ProxyMessageEncoder extends MessageToByteEncoder<ProxyMessage> {
bodyLength += msg.getData().length;
}
// write the total packet length but without length field's length.
out.writeInt(bodyLength);
Attribute<Boolean> booleanAttribute = ctx.attr(Constants.IS_SECURITY);
Boolean isSecurity = booleanAttribute.get();
out.writeByte(msg.getType());
out.writeLong(msg.getSerialNumber());
ByteBuf buf;
// 考虑isSecurity为null的情况,null的情况也为false
if (isSecurity != null && isSecurity) {
buf = Unpooled.directBuffer(bodyLength);
} else {
buf = out;
}
// write the total packet length but without length field's length.
buf.writeInt(bodyLength);
buf.writeByte(msg.getType());
buf.writeLong(msg.getSerialNumber());
if (infoBytes != null) {
out.writeInt(infoBytes.length);
out.writeBytes(infoBytes);
buf.writeInt(infoBytes.length);
buf.writeBytes(infoBytes);
} else {
out.writeInt(0x00);
buf.writeInt(0x00);
}
if (msg.getData() != null) {
out.writeBytes(msg.getData());
buf.writeBytes(msg.getData());
}
// 考虑isSecurity为null的情况,null的情况也为false
if (isSecurity != null && isSecurity) {
// 执行加密
byte[] data = new byte[buf.writerIndex()];
buf.readBytes(data);
// 获取加密密钥
Attribute<byte[]> secureKeyAttr = ctx.attr(SECURE_KEY);
byte[] secureKey = secureKeyAttr.get();
// 执行加密
byte[] encryptedData = EncryptUtil.encryptByAes(secureKey, data);
out.writeInt(encryptedData.length);
out.writeBytes(encryptedData);
buf.release();
}
}
}
@@ -0,0 +1,58 @@
package org.dromara.neutrinoproxy.core.util;
import cn.hutool.core.util.RandomUtil;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Random;
/**
* AES工具
*/
public class AesUtil {
public static byte[] generateKey() {
byte[] keyBytes = new byte[16];
Random random = RandomUtil.getRandom(true);
random.nextBytes(keyBytes);
return keyBytes;
}
/**
* AES解密
* @param decryptKey 秘钥,16位
* @param encryptBytes 密文
* @return 明文
* @throws Exception
*/
public static byte[] decrypt(byte[] decryptKey, byte[] encryptBytes) {
try{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey, "AES"));
return cipher.doFinal(encryptBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* AES加密
* @param encryptKey 秘钥,必须为16个字符组成
* @param data 明文
* @return 密文
* @throws Exception
*/
public static byte[] encrypt(byte[] encryptKey, byte[] data) {
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey, "AES"));
return cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
@@ -0,0 +1,150 @@
/**
* Copyright (c) 2022 aoshiguchen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.dromara.neutrinoproxy.core.util;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.util.encoders.Hex;
import org.dromara.neutrinoproxy.core.KeyPairRecord;
import javax.crypto.SecretKey;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
/**
* 国密算法加解密工具
* @author: az
* @date: 2023/11/07
*/
public class EncryptUtil {
/**
* 生成SM2密钥对
* @return
*/
public static KeyPairRecord generateSm2KeyPair() {
String privateKeyHex = null;
String publicKeyHex = null;
KeyPair keyPair = Sm2Util.createECKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
if (privateKey instanceof BCECPrivateKey) {
//获取32字节十六进制私钥串
privateKeyHex = ((BCECPrivateKey) privateKey).getD().toString(16);
}
PublicKey publicKey = keyPair.getPublic();
if (publicKey instanceof BCECPublicKey) {
//获取65字节非压缩缩的十六进制公钥串(0x04)
publicKeyHex = Hex.toHexString(((BCECPublicKey) publicKey).getQ().getEncoded(false));
}
return new KeyPairRecord(privateKeyHex, publicKeyHex);
}
/**
* 使用SM2算法对数据进行加密
* @param publicKey 加密所需的公钥
* @param data 需要加密的数据
* @return 加密后的字节数组
*/
public static byte[] encryptBySm2(String publicKey, byte[] data) {
return Sm2Util.encrypt(publicKey, data);
}
/**
* 使用SM2算法对数据进行解密
* @param privateKey 解密所需私钥
* @param data 需要解密的数据
* @return 解密后的字节数组
*/
public static byte[] decryptBySm2(String privateKey, byte[] data) {
return Sm2Util.decrypt(privateKey, data);
}
public static byte[] generateSm4Key() {
return SecureUtil.generateKey("AES", 128).getEncoded();
}
/**
* 使用SM4算法加密数据
* @param key 密钥
* @param data 待加密的数据
* @return 已加密的数据
*/
public static byte[] encryptBySm4(byte[] key, byte[] data) {
return SmUtil.sm4(key).encrypt(data);
}
/**
* 使用SM4算法解密数据
* @param key 密钥
* @param encryptedData 已加密数据
* @return 解密后的数据
*/
public static byte[] decryptBySm4(byte[] key, byte[] encryptedData) {
return SmUtil.sm4(key).decrypt(encryptedData);
}
public static byte[] generateAesKey() {
return AesUtil.generateKey();
}
/**
* 使用AES算法加密数据
* @param key 密钥
* @param data 被加密数据
* @return 加密后的数据
*/
public static byte[] encryptByAes(byte[] key, byte[] data) {
return AesUtil.encrypt(key, data);
}
/**
* 使用AES法解密数据
* @param key 密钥
* @param encryptedData 已加密数据
* @return 解密后的数据
*/
public static byte[] decryptByAes(byte[] key, byte[] encryptedData) {
return AesUtil.decrypt(key, encryptedData);
}
/**
* 使用SM3算法对内容生成摘要
* @param data
* @return
*/
public static String digestBySm3(byte[] data) {
return SmUtil.sm3().digestHex(data);
}
}
@@ -0,0 +1,216 @@
package org.dromara.neutrinoproxy.core.util;
import org.bouncycastle.asn1.gm.GMNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.jce.spec.ECPrivateKeySpec;
import org.bouncycastle.jce.spec.ECPublicKeySpec;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.spec.ECGenParameterSpec;
/**
* @ClassName SM2Utils
* @Description SM2算法工具类
*/
public class Sm2Util {
/**
* @Description 生成秘钥对
* @return KeyPair
*/
public static KeyPair createECKeyPair() {
//使用标准名称创建EC参数生成的参数规范
final ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");
// 获取一个椭圆曲线类型的密钥对生成器
final KeyPairGenerator kpg;
try {
kpg = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
// 使用SM2算法域参数集初始化密钥生成器(默认使用以最高优先级安装的提供者的 SecureRandom 的实现作为随机源)
// kpg.initialize(sm2Spec);
// 使用SM2的算法域参数集和指定的随机源初始化密钥生成器
kpg.initialize(sm2Spec, new SecureRandom());
// 通过密钥生成器生成密钥对
return kpg.generateKeyPair();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* @Description 公钥加密
* @param publicKeyHex SM2十六进制公钥
* @param data 明文数据
* @return String
*/
public static byte[] encrypt(String publicKeyHex, byte[] data) {
return encrypt(getECPublicKeyByPublicKeyHex(publicKeyHex), data, 1);
}
/**
* @Description 公钥加密
* @param publicKey SM2公钥
* @param data 明文数据
* @param modeType 加密模式
* @return String
*/
public static byte[] encrypt(BCECPublicKey publicKey, byte[] data, int modeType) {
//加密模式
SM2Engine.Mode mode = SM2Engine.Mode.C1C3C2;
if (modeType != 1) {
mode = SM2Engine.Mode.C1C2C3;
}
//通过公钥对象获取公钥的基本域参数。
ECParameterSpec ecParameterSpec = publicKey.getParameters();
ECDomainParameters ecDomainParameters = new ECDomainParameters(ecParameterSpec.getCurve(),
ecParameterSpec.getG(), ecParameterSpec.getN());
//通过公钥值和公钥基本参数创建公钥参数对象
ECPublicKeyParameters ecPublicKeyParameters = new ECPublicKeyParameters(publicKey.getQ(), ecDomainParameters);
//根据加密模式实例化SM2公钥加密引擎
SM2Engine sm2Engine = new SM2Engine(mode);
//初始化加密引擎
sm2Engine.init(true, new ParametersWithRandom(ecPublicKeyParameters, new SecureRandom()));
byte[] arrayOfBytes = null;
try {
//将明文字符串转换为指定编码的字节串
//通过加密引擎对字节数串行加密
arrayOfBytes = sm2Engine.processBlock(data, 0, data.length);
} catch (Exception e) {
System.out.println("SM2加密时出现异常:" + e.getMessage());
e.printStackTrace();
}
//将加密后的字节串转换为十六进制字符串
return arrayOfBytes;
}
/**
* @Description 私钥解密
* @param privateKeyHex SM2十六进制私钥
* @param cipherData 密文数据
* @return String
*/
public static byte[] decrypt(String privateKeyHex, byte[] cipherData) {
return decrypt(getBCECPrivateKeyByPrivateKeyHex(privateKeyHex), cipherData, 1);
}
/**
* @Description 私钥解密
* @param privateKey SM私钥
* @param cipherDataByte 密文数据
* @param modeType 解密模式
* @return
*/
public static byte[] decrypt(BCECPrivateKey privateKey, byte[] cipherDataByte, int modeType) {
//解密模式
SM2Engine.Mode mode = SM2Engine.Mode.C1C3C2;
if (modeType != 1)
mode = SM2Engine.Mode.C1C2C3;
//通过私钥对象获取私钥的基本域参数。
ECParameterSpec ecParameterSpec = privateKey.getParameters();
ECDomainParameters ecDomainParameters = new ECDomainParameters(ecParameterSpec.getCurve(),
ecParameterSpec.getG(), ecParameterSpec.getN());
//通过私钥值和私钥钥基本参数创建私钥参数对象
ECPrivateKeyParameters ecPrivateKeyParameters = new ECPrivateKeyParameters(privateKey.getD(),
ecDomainParameters);
//通过解密模式创建解密引擎并初始化
SM2Engine sm2Engine = new SM2Engine(mode);
sm2Engine.init(false, ecPrivateKeyParameters);
try {
//通过解密引擎对密文字节串进行解密
return sm2Engine.processBlock(cipherDataByte, 0, cipherDataByte.length);
} catch (Exception e) {
System.out.println("SM2解密时出现异常" + e.getMessage());
}
return new byte[0];
}
//椭圆曲线ECParameters ASN.1 结构
private static X9ECParameters x9ECParameters = GMNamedCurves.getByName("sm2p256v1");
//椭圆曲线公钥或私钥的基本域参数。
private static ECParameterSpec ecDomainParameters = new ECParameterSpec(x9ECParameters.getCurve(), x9ECParameters.getG(), x9ECParameters.getN());
/**
* @Description 公钥字符串转换为 BCECPublicKey 公钥对象
* @param pubKeyHex 64字节十六进制公钥字符串(如果公钥字符串为65字节首个字节为0x04:表示该公钥为非压缩格式,操作时需要删除)
* @return BCECPublicKey SM2公钥对象
*/
public static BCECPublicKey getECPublicKeyByPublicKeyHex(String pubKeyHex) {
//截取64字节有效的SM2公钥(如果公钥首个字节为0x04)
if (pubKeyHex.length() > 128) {
pubKeyHex = pubKeyHex.substring(pubKeyHex.length() - 128);
}
//将公钥拆分为x,y分量(各32字节)
String stringX = pubKeyHex.substring(0, 64);
String stringY = pubKeyHex.substring(stringX.length());
//将公钥x、y分量转换为BigInteger类型
BigInteger x = new BigInteger(stringX, 16);
BigInteger y = new BigInteger(stringY, 16);
//通过公钥x、y分量创建椭圆曲线公钥规范
ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(x9ECParameters.getCurve().createPoint(x, y), ecDomainParameters);
//通过椭圆曲线公钥规范,创建出椭圆曲线公钥对象(可用于SM2加密及验签)
return new BCECPublicKey("EC", ecPublicKeySpec, BouncyCastleProvider.CONFIGURATION);
}
/**
* @Description 私钥字符串转换为 BCECPrivateKey 私钥对象
* @param privateKeyHex 32字节十六进制私钥字符串
* @return BCECPrivateKey SM2私钥对象
*/
public static BCECPrivateKey getBCECPrivateKeyByPrivateKeyHex(String privateKeyHex) {
//将十六进制私钥字符串转换为BigInteger对象
BigInteger d = new BigInteger(privateKeyHex, 16);
//通过私钥和私钥域参数集创建椭圆曲线私钥规范
ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(d, ecDomainParameters);
//通过椭圆曲线私钥规范,创建出椭圆曲线私钥对象(可用于SM2解密和签名)
return new BCECPrivateKey("EC", ecPrivateKeySpec, BouncyCastleProvider.CONFIGURATION);
}
public static void main(String[] args) {
/*String publicKeyHex = null;
String privateKeyHex = null;*/
/*KeyPair keyPair = createECKeyPair();
PublicKey publicKey = keyPair.getPublic();
if (publicKey instanceof BCECPublicKey) {
//获取65字节非压缩缩的十六进制公钥串(0x04)
publicKeyHex = Hex.toHexString(((BCECPublicKey) publicKey).getQ().getEncoded(false));
System.out.println("---->SM2公钥:" + publicKeyHex);
}
PrivateKey privateKey = keyPair.getPrivate();
if (privateKey instanceof BCECPrivateKey) {
//获取32字节十六进制私钥串
privateKeyHex = ((BCECPrivateKey) privateKey).getD().toString(16);
System.out.println("---->SM2私钥:" + privateKeyHex);
}*/
/**
* 公钥加密
*/
// String data = "az";
//将十六进制公钥串转换为 BCECPublicKey 公钥对象
/*String encryptData = encrypt(publicKeyHex, data);
System.out.println("---->加密结果:" + encryptData);*/
/**
* 私钥解密
*/
//将十六进制私钥串转换为 BCECPrivateKey 私钥对象
/*data = decrypt("xx", "xx");
System.out.println("---->解密结果:" + data);*/
}
}
@@ -23,9 +23,10 @@
package org.dromara.neutrinoproxy.server.proxy.handler;
import cn.hutool.core.util.StrUtil;
import org.dromara.neutrinoproxy.core.*;
import io.netty.util.Attribute;
import org.dromara.neutrinoproxy.core.*;
import org.dromara.neutrinoproxy.core.dispatcher.Match;
import org.dromara.neutrinoproxy.core.util.EncryptUtil;
import org.dromara.neutrinoproxy.server.base.proxy.ProxyConfig;
import org.dromara.neutrinoproxy.server.constant.ClientConnectTypeEnum;
import org.dromara.neutrinoproxy.server.constant.EnableStatusEnum;
@@ -90,7 +91,7 @@ public class ProxyMessageAuthHandler implements ProxyMessageHandler {
if (StrUtil.isEmpty(licenseKey)) {
log.warn("[client connection] license cannot empty info:{} ", info);
ctx.channel().writeAndFlush(ProxyMessage.buildAuthResultMessage(ExceptionEnum.AUTH_FAILED.getCode(), "license不能为空!", licenseKey));
ctx.channel().writeAndFlush(ProxyMessage.buildAuthResultMessage(ExceptionEnum.AUTH_FAILED.getCode(), "license不能为空!", licenseKey, null));
ctx.channel().close();
clientConnectRecordService.add(new ClientConnectRecordDO()
.setIp(ip)
@@ -104,22 +105,22 @@ public class ProxyMessageAuthHandler implements ProxyMessageHandler {
}
LicenseDO licenseDO = licenseService.findByKey(licenseKey);
if (null == licenseDO) {
log.warn("[client connection] license notfound info:{} ", info);
ctx.channel().writeAndFlush(ProxyMessage.buildAuthResultMessage(ExceptionEnum.AUTH_FAILED.getCode(), "license不存在!", licenseKey));
log.warn("[client connection] license not found info:{} ", info);
ctx.channel().writeAndFlush(ProxyMessage.buildAuthResultMessage(ExceptionEnum.AUTH_FAILED.getCode(), "license不存在!", licenseKey, null));
ctx.channel().close();
clientConnectRecordService.add(new ClientConnectRecordDO()
.setIp(ip)
.setType(ClientConnectTypeEnum.CONNECT.getType())
.setMsg(licenseKey)
.setCode(SuccessCodeEnum.FAIL.getCode())
.setErr("license notfound!")
.setErr("license not found!")
.setCreateTime(now)
);
return;
}
if (EnableStatusEnum.DISABLE.getStatus().equals(licenseDO.getEnable())) {
log.warn("[client connection] the license disabled info:{} ", info);
ctx.channel().writeAndFlush(ProxyMessage.buildAuthResultMessage(ExceptionEnum.AUTH_FAILED.getCode(), "the license disabled!", licenseKey));
ctx.channel().writeAndFlush(ProxyMessage.buildAuthResultMessage(ExceptionEnum.AUTH_FAILED.getCode(), "the license disabled!", licenseKey, null));
ctx.channel().close();
clientConnectRecordService.add(new ClientConnectRecordDO()
.setIp(ip)
@@ -134,7 +135,7 @@ public class ProxyMessageAuthHandler implements ProxyMessageHandler {
UserDO userDO = userService.findById(licenseDO.getUserId());
if (null == userDO || EnableStatusEnum.DISABLE.getStatus().equals(userDO.getEnable())) {
log.warn("[client connection] the license invalid info:{} ", info);
ctx.channel().writeAndFlush(ProxyMessage.buildAuthResultMessage(ExceptionEnum.AUTH_FAILED.getCode(), "the license invalid!", licenseKey));
ctx.channel().writeAndFlush(ProxyMessage.buildAuthResultMessage(ExceptionEnum.AUTH_FAILED.getCode(), "the license invalid!", licenseKey, null));
ctx.channel().close();
clientConnectRecordService.add(new ClientConnectRecordDO()
.setIp(ip)
@@ -151,7 +152,7 @@ public class ProxyMessageAuthHandler implements ProxyMessageHandler {
String _clientId = ProxyUtil.getClientIdByLicenseId(licenseDO.getId());
if (!clientId.equals(_clientId)) {
log.warn("[client connection] the license on another no used info:{} _clientId:{}", info, _clientId);
ctx.channel().writeAndFlush(ProxyMessage.buildAuthResultMessage(ExceptionEnum.AUTH_FAILED.getCode(), "the license on another no used!", licenseKey));
ctx.channel().writeAndFlush(ProxyMessage.buildAuthResultMessage(ExceptionEnum.AUTH_FAILED.getCode(), "the license on another no used!", licenseKey, null));
ctx.channel().close();
clientConnectRecordService.add(new ClientConnectRecordDO()
.setIp(ip)
@@ -164,8 +165,22 @@ public class ProxyMessageAuthHandler implements ProxyMessageHandler {
return;
}
}
// 存储状态为非安全,如果客户端响应以下的公钥信息,则在响应中设置为安全
Attribute<Boolean> booleanAttribute = ctx.attr(Constants.IS_SECURITY);
booleanAttribute.set(false);
// 生成获取SM2密钥对,私钥存入ctx,公钥拼装参数随Auth数据包返回
KeyPairRecord record = EncryptUtil.generateSm2KeyPair();
// 私钥存入ctx
ctx.attr(Constants.SECURE_PRIVATE_KEY).set(record.privateKey());
// 存储licenseId
ctx.attr(Constants.LICENSE_ID).set(licenseDO.getId());
// 发送认证成功消息
ctx.channel().writeAndFlush(ProxyMessage.buildAuthResultMessage(ExceptionEnum.SUCCESS.getCode(), "auth success!", licenseKey));
ctx.channel().writeAndFlush(ProxyMessage.buildAuthResultMessage(ExceptionEnum.SUCCESS.getCode(), "auth success!", licenseKey, record.publicKey()));
clientConnectRecordService.add(new ClientConnectRecordDO()
.setIp(ip)
@@ -92,6 +92,9 @@ public class ProxyMessageConnectHandler implements ProxyMessageHandler {
ProxyUtil.remoteProxyConnectAttachment(visitorId);
proxyAttachment.execute();
}
// 设置加密
ProxyUtil.setChannelSecurity(licenseDO.getId(), ctx.channel());
}
@Override
@@ -0,0 +1,75 @@
package org.dromara.neutrinoproxy.server.proxy.handler;
import cn.hutool.core.util.StrUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import lombok.extern.slf4j.Slf4j;
import org.dromara.neutrinoproxy.core.Constants;
import org.dromara.neutrinoproxy.core.ProxyDataTypeEnum;
import org.dromara.neutrinoproxy.core.ProxyMessage;
import org.dromara.neutrinoproxy.core.ProxyMessageHandler;
import org.dromara.neutrinoproxy.core.dispatcher.Match;
import org.dromara.neutrinoproxy.core.util.EncryptUtil;
import org.dromara.neutrinoproxy.server.util.ProxyUtil;
import org.noear.solon.annotation.Component;
import java.util.Map;
@Slf4j
@Match(type= Constants.ProxyDataTypeName.SECURE_KEY)
@Component
public class ProxyMessageSecureKeyHandler implements ProxyMessageHandler {
@Override
public void handle(ChannelHandlerContext ctx, ProxyMessage proxyMessage) {
log.info("收到客户端的加密信息");
// data为加密后的密码,info为加密密码的摘要
byte[] data = proxyMessage.getData();
String receivedDigest = proxyMessage.getInfo();
String digest = EncryptUtil.digestBySm3(data);
if (!digest.equals(receivedDigest)) {
// 获取加密信息失败
log.warn("密码协商失败");
// TODO 应该断开连接
return;
}
// 获取私钥
Attribute<String> privateKeyAttr = ctx.attr(Constants.SECURE_PRIVATE_KEY);
String privateKey = privateKeyAttr.get();
if (StrUtil.isEmpty(privateKey)) {
// 获取私钥失败
log.warn("获取私钥失败");
// TODO 应该断开连接
return;
}
// 解密传输密码
byte[] secureKey = EncryptUtil.decryptBySm2(privateKey, data);
// 传输密码存储ctx中
Attribute<byte[]> secureKeyAttr = ctx.attr(Constants.SECURE_KEY);
secureKeyAttr.setIfAbsent(secureKey);
// 使用密码加密success给客户端表示密码已确认
byte[] encryptedSuccessInfoData = EncryptUtil.encryptByAes(secureKey, "ok".getBytes());
// 发送回去,以示确认
ctx.writeAndFlush(ProxyMessage.buildSecureKeyReturnMessage(encryptedSuccessInfoData));
ctx.flush();
// 设置该链路以及相关链路状态为安全,之后使用链路传输的数据均会加密
Integer licenseId = ctx.attr(Constants.LICENSE_ID).get();
ProxyUtil.setSecureKey(licenseId, secureKey);
ProxyUtil.setChannelSecurity(licenseId, ctx.channel());
}
@Override
public String name() {
return ProxyDataTypeEnum.SECURE_KEY.getDesc();
}
}
@@ -38,15 +38,15 @@ public class ProxyUtil {
/**
* 服务端口 -> 指令通道映射
*/
private static Map<Integer, Channel> serverPortToCmdChannelMap = new ConcurrentHashMap<>();
private static final Map<Integer, Channel> serverPortToCmdChannelMap = new ConcurrentHashMap<>();
/**
* license -> 指令通道映射
*/
private static Map<Integer, Channel> licenseToCmdChannelMap = new ConcurrentHashMap<>();
private static final Map<Integer, Channel> licenseToCmdChannelMap = new ConcurrentHashMap<>();
/**
* 服务端口 -> 访问通道映射
*/
private static Map<Integer, Channel> serverPortToVisitorChannel = new ConcurrentHashMap<>();
private static final Map<Integer, Channel> serverPortToVisitorChannel = new ConcurrentHashMap<>();
/**
* cmdChannelAttachInfo.getUserChannelMap() 读写锁
@@ -55,19 +55,21 @@ public class ProxyUtil {
/**
* 访问者ID生成器
*/
private static AtomicLong visitorIdProducer = new AtomicLong(0);
private static final AtomicLong visitorIdProducer = new AtomicLong(0);
/**
* 代理 - connect附加映射
*/
private static Map<String, ProxyAttachment> proxyConnectAttachmentMap = new HashMap<>();
private static final Map<String, ProxyAttachment> proxyConnectAttachmentMap = new HashMap<>();
/**
* 子域名 - 服务端端口映射
*/
private static Map<String, Integer> subdomainToServerPort = new HashMap<>();
private static final Map<String, Integer> subdomainToServerPort = new HashMap<>();
/**
* licenseId - 客户端Id映射
*/
private static Map<Integer, String> licenseIdToClientIdMap = new HashMap<>();
private static final Map<Integer, String> licenseIdToClientIdMap = new HashMap<>();
private static final Map<Integer, byte[]> licenseIdToSecureKeyMap = new ConcurrentHashMap<>();
/**
* 初始化代理信息
@@ -421,4 +423,22 @@ public class ProxyUtil {
public static void removeClientIdByLicenseId(Integer licenseId) {
licenseIdToClientIdMap.remove(licenseId);
}
public static void setSecureKey(Integer licenseId, byte[] key) {
licenseIdToSecureKeyMap.put(licenseId, key);
}
public static void setLicenseIdRelativeProxyChannelSecurity(Integer licenseId) {
Set<Integer> portSet = licenseToServerPortMap.get(licenseId);
for(Integer port : portSet) {
// TODO 代理客户端
}
}
public static void setChannelSecurity(Integer licenseId, Channel channel) {
if (channel != null && licenseIdToSecureKeyMap.containsKey(licenseId)) {
channel.attr(Constants.IS_SECURITY).set(true);
channel.attr(Constants.SECURE_KEY).set(licenseIdToSecureKeyMap.get(licenseId));
}
}
}
@@ -24,7 +24,7 @@ solon.logging.logger:
neutrino:
proxy:
protocol:
max-frame-length: ${MAX_FRAME_LENGTH:2097152}
max-frame-length: ${MAX_FRAME_LENGTH:1048576000}
length-field-offset: 0
length-field-length: 4
initial-bytes-to-strip: 0
+1 -1
View File
@@ -1 +1 @@
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion>␍␍ <parent><groupId>org.noear</groupId><artifactId>solon-parent</artifactId><version>2.5.12</version><relativePath /></parent>␍␍ <groupId>org.dromara.neutrino-proxy</groupId><artifactId>neutrino-proxy</artifactId><packaging>pom</packaging><version>${revision}</version>␍␍ <modules><module>neutrino-proxy-core</module><module>neutrino-proxy-client</module><module>neutrino-proxy-server</module></modules>␍␍ <properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><maven.compiler.encoding>UTF-8</maven.compiler.encoding><revision>2.0.1-SNAPSHOT</revision>␍␍ <native.version>0.9.28</native.version>␍␍ <java.version>21</java.version><maven-compiler-plugin.version>3.8.0</maven-compiler-plugin.version><maven-flatten.version>1.1.0</maven-flatten.version></properties>␍␍ <dependencyManagement><dependencies><dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.100.Final</version></dependency><dependency><groupId>org.yaml</groupId><artifactId>snakeyaml</artifactId><version>1.33</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.9</version></dependency><dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>28.0-jre</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency><dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>2.2.224</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.33</version></dependency><dependency><groupId>org.mariadb.jdbc</groupId><artifactId>mariadb-java-client</artifactId><version>2.7.4</version></dependency><dependency><groupId>com.zaxxer</groupId><artifactId>HikariCP</artifactId><version>4.0.3</version></dependency><dependency><groupId>org.dromara.solon-plugins</groupId><artifactId>job-solon-plugin</artifactId><version>0.1.1</version><exclusions><exclusion><groupId>cn.hutool</groupId><artifactId>hutool-core</artifactId></exclusion></exclusions></dependency></dependencies></dependencyManagement>␍␍ <dependencies><dependency><groupId>org.noear</groupId><artifactId>solon.logging.logback</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>provided</scope></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency><dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId></dependency>␍␍ <dependency><groupId>org.noear</groupId><artifactId>solon-test</artifactId><scope>test</scope></dependency></dependencies>␍␍ <build><resources><resource><directory>src/main/resources</directory></resource></resources><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>${maven-compiler-plugin.version}</version><configuration><source>${java.version}</source><target>${java.version}</target><encoding>UTF-8</encoding><annotationProcessorPaths><path><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>${lombok.version}</version></path></annotationProcessorPaths></configuration></plugin><!-- 添加flatten-maven-plugin插件 --><plugin><groupId>org.codehaus.mojo</groupId><artifactId>flatten-maven-plugin</artifactId><version>${maven-flatten.version}</version><configuration><updatePomFile>true</updatePomFile><flattenMode>resolveCiFriendliesOnly</flattenMode></configuration><executions><execution><id>flatten</id><phase>process-resources</phase><goals><goal>flatten</goal></goals></execution><execution><id>flatten.clean</id><phase>clean</phase><goals><goal>clean</goal></goals></execution></executions></plugin></plugins></build>␍␍ <repositories><repository><id>tencent</id><url>https://mirrors.cloud.tencent.com/nexus/repository/maven-public/</url><snapshots><enabled>false</enabled></snapshots></repository><repository><id>sonatype-nexus-snapshots</id><name>Sonatype Nexus Snapshots</name><url>https://oss.sonatype.org/content/repositories/snapshots</url><releases><enabled>false</enabled></releases></repository></repositories><pluginRepositories><pluginRepository><id>sonatype-nexus-snapshots</id><name>Sonatype Nexus Snapshots</name><url>https://oss.sonatype.org/content/repositories/snapshots</url><releases><enabled>false</enabled></releases></pluginRepository></pluginRepositories>␍␍ <profiles><profile><id>native</id><build><plugins><plugin><groupId>org.noear</groupId><artifactId>solon-maven-plugin</artifactId><version>${solon.version}</version><executions><execution><id>process-aot</id><goals><goal>process-aot</goal></goals></execution></executions>␍␍ <dependencies><dependency><groupId>org.codehaus.plexus</groupId><artifactId>plexus-utils</artifactId><version>3.5.1</version></dependency></dependencies></plugin><plugin><groupId>org.graalvm.buildtools</groupId><artifactId>native-maven-plugin</artifactId><version>${native.version}</version><!-- 使用graalvm提供的可达性元数据,很多第三方库就直接可以构建成可执行文件了 --><configuration><metadataRepository><enabled>true</enabled></metadataRepository></configuration><executions><execution><id>add-reachability-metadata</id><goals><goal>add-reachability-metadata</goal></goals></execution></executions></plugin></plugins></build></profile></profiles></project>␍␍
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion>␍␍ <parent><groupId>org.noear</groupId><artifactId>solon-parent</artifactId><version>2.5.12</version><relativePath /></parent>␍␍ <groupId>org.dromara.neutrino-proxy</groupId><artifactId>neutrino-proxy</artifactId><packaging>pom</packaging><version>${revision}</version>␍␍ <modules><module>neutrino-proxy-core</module><module>neutrino-proxy-client</module><module>neutrino-proxy-server</module></modules>␍␍ <properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><maven.compiler.encoding>UTF-8</maven.compiler.encoding><revision>2.0.1-SNAPSHOT</revision>␍␍ <native.version>0.9.28</native.version>␍␍ <java.version>21</java.version><maven-compiler-plugin.version>3.8.0</maven-compiler-plugin.version><maven-flatten.version>1.1.0</maven-flatten.version></properties>␍␍ <dependencyManagement><dependencies><dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.100.Final</version></dependency><dependency><groupId>org.yaml</groupId><artifactId>snakeyaml</artifactId><version>1.33</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.9</version></dependency><dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>28.0-jre</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency><dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>2.2.224</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.33</version></dependency><dependency><groupId>org.mariadb.jdbc</groupId><artifactId>mariadb-java-client</artifactId><version>2.7.4</version></dependency><dependency><groupId>com.zaxxer</groupId><artifactId>HikariCP</artifactId><version>4.0.3</version></dependency><dependency> <groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk15to18</artifactId><version>1.69</version></dependency><dependency> <groupId>org.dromara.solon-plugins</groupId><artifactId>job-solon-plugin</artifactId><version>0.1.1</version><exclusions><exclusion><groupId>cn.hutool</groupId><artifactId>hutool-core</artifactId></exclusion></exclusions></dependency></dependencies></dependencyManagement>␍␍ <dependencies><dependency><groupId>org.noear</groupId><artifactId>solon.logging.logback</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><scope>provided</scope></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency><dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId></dependency>␍␍ <dependency><groupId>org.noear</groupId><artifactId>solon-test</artifactId><scope>test</scope></dependency></dependencies>␍␍ <build><resources><resource><directory>src/main/resources</directory></resource></resources><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>${maven-compiler-plugin.version}</version><configuration><source>${java.version}</source><target>${java.version}</target><encoding>UTF-8</encoding><annotationProcessorPaths><path><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>${lombok.version}</version></path></annotationProcessorPaths></configuration></plugin><!-- 添加flatten-maven-plugin插件 --><plugin><groupId>org.codehaus.mojo</groupId><artifactId>flatten-maven-plugin</artifactId><version>${maven-flatten.version}</version><configuration><updatePomFile>true</updatePomFile><flattenMode>resolveCiFriendliesOnly</flattenMode></configuration><executions><execution><id>flatten</id><phase>process-resources</phase><goals><goal>flatten</goal></goals></execution><execution><id>flatten.clean</id><phase>clean</phase><goals><goal>clean</goal></goals></execution></executions></plugin></plugins></build>␍␍ <repositories><repository><id>tencent</id><url>https://mirrors.cloud.tencent.com/nexus/repository/maven-public/</url><snapshots><enabled>false</enabled></snapshots></repository><repository><id>sonatype-nexus-snapshots</id><name>Sonatype Nexus Snapshots</name><url>https://oss.sonatype.org/content/repositories/snapshots</url><releases><enabled>false</enabled></releases></repository></repositories><pluginRepositories><pluginRepository><id>sonatype-nexus-snapshots</id><name>Sonatype Nexus Snapshots</name><url>https://oss.sonatype.org/content/repositories/snapshots</url><releases><enabled>false</enabled></releases></pluginRepository></pluginRepositories>␍␍ <profiles><profile><id>native</id><build><plugins><plugin><groupId>org.noear</groupId><artifactId>solon-maven-plugin</artifactId><version>${solon.version}</version><executions><execution><id>process-aot</id><goals><goal>process-aot</goal></goals></execution></executions>␍␍ <dependencies><dependency><groupId>org.codehaus.plexus</groupId><artifactId>plexus-utils</artifactId><version>3.5.1</version></dependency></dependencies></plugin><plugin><groupId>org.graalvm.buildtools</groupId><artifactId>native-maven-plugin</artifactId><version>${native.version}</version><!-- 使用graalvm提供的可达性元数据,很多第三方库就直接可以构建成可执行文件了 --><configuration><metadataRepository><enabled>true</enabled></metadataRepository></configuration><executions><execution><id>add-reachability-metadata</id><goals><goal>add-reachability-metadata</goal></goals></execution></executions></plugin></plugins></build></profile></profiles></project>␍␍