!40 链路使用国密算法对链路进行加密,保证传输过程中信息的机密性

Merge pull request !40 from NichenFly/dev
This commit is contained in:
傲世孤尘
2023-11-08 06:40:50 +00:00
committed by Gitee
17 changed files with 421 additions and 36 deletions
+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",
@@ -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.SmEncryptUtil;
import org.noear.snack.ONode;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Component;
@@ -42,5 +44,21 @@ public class ProxyMessageAuthHandler implements ProxyMessageHandler {
){
context.channel().close();
}
// 默认设置为非安全链路,需要服务端确认后,再设置为安全链路
Attribute<Boolean> booleanAttribute = context.attr(Constants.IS_SECURITY);
booleanAttribute.set(false);
// 获取认证成功的后的公钥信息,并生成随机密码,加密发到服务端确认
String publicKey = load.get("publicKey").getString();
byte[] secureKey = SmEncryptUtil.generateSm4Key();
// 存储密码
Attribute<byte[]> secureKeyAttr = context.attr(Constants.SECURE_KEY);
secureKeyAttr.set(secureKey);
// 使用SM2算法对密钥进行加密并发送到服务端
byte[] encryptSecureKey = SmEncryptUtil.encryptBySm2(publicKey, secureKey);
context.writeAndFlush(ProxyMessage.buildSecureKeyMessage(encryptSecureKey));
context.flush();
}
}
@@ -0,0 +1,34 @@
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.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.SmEncryptUtil;
import org.noear.solon.annotation.Component;
@Slf4j
@Match(type = Constants.ProxyDataTypeName.SECURE_KEY)
@Component
public class ProxyMessageSecureKeyHandler implements ProxyMessageHandler {
@Override
public void handle(ChannelHandlerContext ctx, ProxyMessage proxyMessage) {
log.info("收到服务端的加密确认");
Attribute<byte[]> secureKeyAttr = ctx.attr(Constants.SECURE_KEY);
byte[] secureKey = secureKeyAttr.get();
byte[] data = proxyMessage.getData();
byte[] decryptedData = SmEncryptUtil.decryptBySm4(secureKey, data);
String m = new String(decryptedData);
if ("ok".equals(m)) {
// 设置当前链路为安全,之后使用该链路传输的消息均会加密
Attribute<Boolean> booleanAttribute = ctx.attr(Constants.IS_SECURITY);
booleanAttribute.set(true);
log.info("Encrypted link established successfully");
} else {
ctx.channel().close();
}
}
}
@@ -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
@@ -40,11 +40,11 @@ neutrino:
# 服务端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.SmEncryptUtil;
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(SmEncryptUtil.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)
@@ -23,10 +23,16 @@
package org.dromara.neutrinoproxy.core;
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.SmEncryptUtil;
import static org.dromara.neutrinoproxy.core.Constants.*;
@Slf4j
/**
*
* @author: aoshiguchen
@@ -70,28 +76,55 @@ 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) {
log.info("执行解密逻辑");
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 = SmEncryptUtil.decryptBySm4(secureKey, encryptedBytes);
buf = Unpooled.wrappedBuffer(decryptedData);
} else {
buf = in;
log.info("链路不加密解码");
}
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;
}
@@ -23,8 +23,13 @@
package org.dromara.neutrinoproxy.core;
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.SmEncryptUtil;
import static org.dromara.neutrinoproxy.core.Constants.*;
/**
@@ -32,6 +37,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 +46,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 +58,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) {
log.info("执行加密逻辑");
buf = Unpooled.buffer(bodyLength);
} else {
log.info("不执行加密的链路编码");
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[bodyLength];
buf.readBytes(data);
// 获取加密密钥
Attribute<byte[]> secureKeyAttr = ctx.attr(SECURE_KEY);
byte[] secureKey = secureKeyAttr.get();
// 执行加密
byte[] encryptedData = SmEncryptUtil.encryptBySm4(secureKey, data);
out.writeByte(encryptedData.length);
out.writeBytes(encryptedData);
}
}
}
@@ -0,0 +1,109 @@
/**
* 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 org.dromara.neutrinoproxy.core.KeyPairRecord;
import javax.crypto.SecretKey;
import java.security.KeyPair;
/**
* 国密算法加解密工具
* @author: az
* @date: 2023/11/07
*/
public class SmEncryptUtil {
/**
* 生成SM2密钥对
* @return
*/
public static KeyPairRecord generateSm2KeyPair() {
KeyPair keyPair = SecureUtil.generateKeyPair("SM2");
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
String privateKey = HexUtil.encodeHexStr(privateKeyBytes);
String publicKey = HexUtil.encodeHexStr(publicKeyBytes);
return new KeyPairRecord(privateKey, publicKey);
}
/**
* 使用SM2算法对数据进行加密
* @param publicKey 加密所需的公钥
* @param data 需要加密的数据
* @return 加密后的字节数组
*/
public static byte[] encryptBySm2(String publicKey, byte[] data) {
return SmUtil.sm2(null, publicKey).encrypt(data);
}
/**
* 使用SM2算法对数据进行解密
* @param privateKey 解密所需私钥
* @param data 需要解密的数据
* @return 解密后的字节数组
*/
public static byte[] decryptBySm2(String privateKey, byte[] data) {
return SmUtil.sm2(privateKey, null).decrypt(data);
}
public static byte[] generateSm4Key() {
SecretKey key = SecureUtil.generateKey("AES", 128);
return key.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);
}
/**
* 使用SM3算法对内容生成摘要
* @param data
* @return
*/
public static String digestBySm3(byte[] data) {
return SmUtil.sm3().digestHex(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.SmEncryptUtil;
import org.dromara.neutrinoproxy.server.base.proxy.ProxyConfig;
import org.dromara.neutrinoproxy.server.constant.ClientConnectTypeEnum;
import org.dromara.neutrinoproxy.server.constant.EnableStatusEnum;
@@ -76,6 +77,8 @@ public class ProxyMessageAuthHandler implements ProxyMessageHandler {
@Override
public void handle(ChannelHandlerContext ctx, ProxyMessage proxyMessage) {
log.info("收到客户端的认证连接信息");
String ip = ((InetSocketAddress)ctx.channel().remoteAddress()).getAddress().getHostAddress();
Date now = new Date();
@@ -90,7 +93,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 +107,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 +137,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 +154,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 +167,20 @@ public class ProxyMessageAuthHandler implements ProxyMessageHandler {
return;
}
}
// 存储状态为非安全,如果客户端响应以下的公钥信息,则在响应中设置为安全
Attribute<Boolean> booleanAttribute = ctx.attr(Constants.IS_SECURITY);
booleanAttribute.set(false);
// 生成获取SM2密钥对,私钥存入ctx,公钥拼装参数随Auth数据包返回
KeyPairRecord record = SmEncryptUtil.generateSm2KeyPair();
// 私钥存入ctx
Attribute<String> attr = ctx.attr(Constants.SECURE_PRIVATE_KEY);
attr.set(record.privateKey());
// 发送认证成功消息
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)
@@ -0,0 +1,71 @@
package org.dromara.neutrinoproxy.server.proxy.handler;
import cn.hutool.core.util.StrUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
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.SmEncryptUtil;
import org.noear.solon.annotation.Component;
@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 = SmEncryptUtil.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 = SmEncryptUtil.decryptBySm2(privateKey, data);
// 传输密码存储ctx中
Attribute<byte[]> secureKeyAttr = ctx.attr(Constants.SECURE_KEY);
secureKeyAttr.setIfAbsent(secureKey);
// 使用密码加密success给客户端表示密码已确认
byte[] encryptedSuccessInfoData = SmEncryptUtil.encryptBySm4(secureKey, "ok".getBytes());
// 发送回去,以示确认
ctx.writeAndFlush(ProxyMessage.buildSecureKeyReturnMessage(encryptedSuccessInfoData));
ctx.flush();
// 设置链路状态为安全,之后使用该链路传输的均会加密
Attribute<Boolean> booleanAttribute = ctx.attr(Constants.IS_SECURITY);
booleanAttribute.set(true);
}
@Override
public String name() {
return ProxyDataTypeEnum.SECURE_KEY.getDesc();
}
}
@@ -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>␍␍