!42 解决加密链路解码异常问题

Merge pull request !42 from NichenFly/dev
This commit is contained in:
傲世孤尘
2023-11-14 13:38:17 +00:00
committed by Gitee
13 changed files with 134 additions and 36 deletions
@@ -9,7 +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.dromara.neutrinoproxy.core.util.EncryptUtil;
import org.noear.snack.ONode;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Component;
@@ -51,13 +51,13 @@ public class ProxyMessageAuthHandler implements ProxyMessageHandler {
// 获取认证成功的后的公钥信息,并生成随机密码,加密发到服务端确认
String publicKey = load.get("publicKey").getString();
byte[] secureKey = SmEncryptUtil.generateSm4Key();
byte[] secureKey = EncryptUtil.generateAesKey();
// 存储密码
Attribute<byte[]> secureKeyAttr = context.attr(Constants.SECURE_KEY);
secureKeyAttr.set(secureKey);
// 使用SM2算法对密钥进行加密并发送到服务端
byte[] encryptSecureKey = SmEncryptUtil.encryptBySm2(publicKey, secureKey);
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
@@ -3,11 +3,12 @@ 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.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.SmEncryptUtil;
import org.dromara.neutrinoproxy.core.util.EncryptUtil;
import org.noear.solon.annotation.Component;
@Slf4j
@@ -20,12 +21,16 @@ public class ProxyMessageSecureKeyHandler implements ProxyMessageHandler {
Attribute<byte[]> secureKeyAttr = ctx.attr(Constants.SECURE_KEY);
byte[] secureKey = secureKeyAttr.get();
byte[] data = proxyMessage.getData();
byte[] decryptedData = SmEncryptUtil.decryptBySm4(secureKey, data);
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;
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);
}
}
@@ -24,7 +24,7 @@ package org.dromara.neutrinoproxy.core;
import lombok.Data;
import lombok.experimental.Accessors;
import org.dromara.neutrinoproxy.core.util.SmEncryptUtil;
import org.dromara.neutrinoproxy.core.util.EncryptUtil;
import org.noear.snack.ONode;
import java.util.Arrays;
@@ -145,7 +145,7 @@ public class ProxyMessage {
public static ProxyMessage buildSecureKeyMessage(byte[] secureKey) {
return create().setType(TYPE_SECURE_KEY)
.setInfo(SmEncryptUtil.digestBySm3(secureKey))
.setInfo(EncryptUtil.digestBySm3(secureKey))
.setData(secureKey);
}
@@ -22,13 +22,14 @@
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.SmEncryptUtil;
import org.dromara.neutrinoproxy.core.util.EncryptUtil;
import static org.dromara.neutrinoproxy.core.Constants.*;
@@ -97,7 +98,7 @@ public class ProxyMessageDecoder extends LengthFieldBasedFrameDecoder {
Attribute<byte[]> secureKeyAttr = ctx.attr(SECURE_KEY);
byte[] secureKey = secureKeyAttr.get();
// 解密
byte[] decryptedData = SmEncryptUtil.decryptBySm4(secureKey, encryptedBytes);
byte[] decryptedData = EncryptUtil.decryptByAes(secureKey, encryptedBytes);
buf = Unpooled.wrappedBuffer(decryptedData);
} else {
@@ -110,7 +111,6 @@ public class ProxyMessageDecoder extends LengthFieldBasedFrameDecoder {
long sn = buf.readLong();
proxyMessage.setSerialNumber(sn);
proxyMessage.setType(type);
int infoLength = buf.readInt();
@@ -124,6 +124,10 @@ public class ProxyMessageDecoder extends LengthFieldBasedFrameDecoder {
buf.release();
if (isSecurity != null && isSecurity) {
log.info("【ProxyMessage】-type:{},编码解密", proxyMessage.getType());
}
return proxyMessage;
}
}
@@ -22,13 +22,14 @@
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.SmEncryptUtil;
import org.dromara.neutrinoproxy.core.util.EncryptUtil;
import static org.dromara.neutrinoproxy.core.Constants.*;
@@ -89,6 +90,9 @@ public class ProxyMessageEncoder extends MessageToByteEncoder<ProxyMessage> {
// 考虑isSecurity为null的情况,null的情况也为false
if (isSecurity != null && isSecurity) {
log.info("【ProxyMessage】-type:{},编码加密", msg.getType());
// 执行加密
byte[] data = new byte[buf.writerIndex()];
buf.readBytes(data);
@@ -97,9 +101,10 @@ public class ProxyMessageEncoder extends MessageToByteEncoder<ProxyMessage> {
Attribute<byte[]> secureKeyAttr = ctx.attr(SECURE_KEY);
byte[] secureKey = secureKeyAttr.get();
// 执行加密
byte[] encryptedData = SmEncryptUtil.encryptBySm4(secureKey, data);
byte[] encryptedData = EncryptUtil.encryptByAes(secureKey, data);
out.writeInt(encryptedData.length);
out.writeBytes(encryptedData);
buf.release();
}
}
@@ -25,6 +25,8 @@ 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.dromara.neutrinoproxy.core.KeyPairRecord;
import javax.crypto.SecretKey;
@@ -35,7 +37,7 @@ import java.security.KeyPair;
* @author: az
* @date: 2023/11/07
*/
public class SmEncryptUtil {
public class EncryptUtil {
/**
* 生成SM2密钥对
@@ -73,8 +75,7 @@ public class SmEncryptUtil {
}
public static byte[] generateSm4Key() {
SecretKey key = SecureUtil.generateKey("AES", 128);
return key.getEncoded();
return SecureUtil.generateKey("AES", 128).getEncoded();
}
/**
@@ -97,6 +98,32 @@ public class SmEncryptUtil {
return SmUtil.sm4(key).decrypt(encryptedData);
}
public static byte[] generateAesKey() {
return SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
}
/**
* 使用AES算法加密数据
* @param key 密钥
* @param data 被加密数据
* @return 加密后的数据
*/
public static byte[] encryptByAes(byte[] key, byte[] data) {
SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
return aes.encrypt(data);
}
/**
* 使用AES法解密数据
* @param key 密钥
* @param encryptedData 已加密数据
* @return 解密后的数据
*/
public static byte[] decryptByAes(byte[] key, byte[] encryptedData) {
SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
return aes.decrypt(encryptedData);
}
/**
* 使用SM3算法对内容生成摘要
* @param data
@@ -26,7 +26,7 @@ import cn.hutool.core.util.StrUtil;
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.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;
@@ -173,11 +173,13 @@ public class ProxyMessageAuthHandler implements ProxyMessageHandler {
booleanAttribute.set(false);
// 生成获取SM2密钥对,私钥存入ctx,公钥拼装参数随Auth数据包返回
KeyPairRecord record = SmEncryptUtil.generateSm2KeyPair();
KeyPairRecord record = EncryptUtil.generateSm2KeyPair();
// 私钥存入ctx
Attribute<String> attr = ctx.attr(Constants.SECURE_PRIVATE_KEY);
attr.set(record.privateKey());
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, record.publicKey()));
@@ -92,6 +92,9 @@ public class ProxyMessageConnectHandler implements ProxyMessageHandler {
ProxyUtil.remoteProxyConnectAttachment(visitorId);
proxyAttachment.execute();
}
// 设置加密
ProxyUtil.setChannelSecurity(licenseDO.getId(), ctx.channel());
}
@Override
@@ -1,18 +1,21 @@
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 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.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
@@ -27,7 +30,7 @@ public class ProxyMessageSecureKeyHandler implements ProxyMessageHandler {
byte[] data = proxyMessage.getData();
String receivedDigest = proxyMessage.getInfo();
String digest = SmEncryptUtil.digestBySm3(data);
String digest = EncryptUtil.digestBySm3(data);
if (!digest.equals(receivedDigest)) {
// 获取加密信息失败
log.warn("密码协商失败");
@@ -46,22 +49,23 @@ public class ProxyMessageSecureKeyHandler implements ProxyMessageHandler {
}
// 解密传输密码
byte[] secureKey = SmEncryptUtil.decryptBySm2(privateKey, data);
byte[] secureKey = EncryptUtil.decryptBySm2(privateKey, data);
// 传输密码存储ctx中
Attribute<byte[]> secureKeyAttr = ctx.attr(Constants.SECURE_KEY);
secureKeyAttr.setIfAbsent(secureKey);
// 使用密码加密success给客户端表示密码已确认
byte[] encryptedSuccessInfoData = SmEncryptUtil.encryptBySm4(secureKey, "ok".getBytes());
byte[] encryptedSuccessInfoData = EncryptUtil.encryptByAes(secureKey, "ok".getBytes());
// 发送回去,以示确认
ctx.writeAndFlush(ProxyMessage.buildSecureKeyReturnMessage(encryptedSuccessInfoData));
ctx.flush();
// 设置链路状态为安全,之后使用链路传输的均会加密
Attribute<Boolean> booleanAttribute = ctx.attr(Constants.IS_SECURITY);
booleanAttribute.set(true);
// 设置该链路以及相关链路状态为安全,之后使用链路传输的数据均会加密
Integer licenseId = ctx.attr(Constants.LICENSE_ID).get();
ProxyUtil.setSecureKey(licenseId, secureKey);
ProxyUtil.setChannelSecurity(licenseId, ctx.channel());
}
@Override
@@ -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));
}
}
}