diff --git a/config/application-local.properties b/config/application-local.properties index 0180f799..83fc0149 100644 --- a/config/application-local.properties +++ b/config/application-local.properties @@ -5,7 +5,7 @@ server.tomcat.basedir=./basedir server.servlet.context-path=/dispose # 配置数据源 spring.datasource.url=jdbc:mysql://10.88.77\ - .65:33061/dispose_cl_areacode_v2?serverTimezone=Asia/Shanghai&zeroDateTimeBehavior\ + .65:33061/dispose_cl_huaweifirewall?serverTimezone=Asia/Shanghai&zeroDateTimeBehavior\ =convertToNull&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=root diff --git a/pom.xml b/pom.xml index 0d1e13d1..dc4f69bb 100644 --- a/pom.xml +++ b/pom.xml @@ -216,6 +216,11 @@ hibernate-validator 6.1.5.Final + + dom4j + dom4j-core + 1.4-dev-8 + diff --git a/src/main/java/com/dispose/ability/impl/HuaWeiFireWallAbilityImpl.java b/src/main/java/com/dispose/ability/impl/HuaWeiFireWallAbilityImpl.java new file mode 100644 index 00000000..469f3565 --- /dev/null +++ b/src/main/java/com/dispose/ability/impl/HuaWeiFireWallAbilityImpl.java @@ -0,0 +1,404 @@ +package com.dispose.ability.impl; + +import cn.hutool.http.HttpResponse; +import com.dispose.ability.DisposeAbility; +import com.dispose.common.DisposeCapacityType; +import com.dispose.common.DisposeConfigValue; +import com.dispose.common.DisposeObjectType; +import com.dispose.common.ErrorCode; + +import com.dispose.common.NetflowDirection; +import com.dispose.pojo.entity.ServiceInfo; +import com.dispose.pojo.po.MulReturnType; +import com.dispose.pojo.vo.DeviceFirewareInfo; +import com.dispose.security.arithmetic.CryptoHelper; +import com.huaweifirewall.dispose.common.HuaWeiFireWallCreatePolicyReq; +import com.huaweifirewall.dispose.common.SourceIp; +import com.huaweifirewall.dispose.protocol.HuaWeiFireWallInterface; +import inet.ipaddr.IPAddress; +import inet.ipaddr.IPAddressString; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.jetbrains.annotations.Nullable; + +import javax.servlet.http.HttpServletResponse; +import java.nio.charset.StandardCharsets; +import java.util.List; + +/** + * @author Nicole + */ +@Slf4j +public class HuaWeiFireWallAbilityImpl implements DisposeAbility { + /** + * The Restful interface. + */ + private final HuaWeiFireWallInterface restfulInterface = new HuaWeiFireWallInterface(); + /** + * The policy name prefix. + */ + private static final String POLICY_NAME_PREFIX = "C_"; + /** + * The Timer cnt. + */ + private long timerCnt = 0; + /** + * The Device link status. + */ + private boolean deviceLinkStatus = false; + /** + * The Url root path. + */ + @Getter + @Setter + private String urlRootPath; + + /** + * The Username. + */ + @Getter + @Setter + private String username; + + /** + * The Password. + */ + @Getter + @Setter + private String password; + + /** + * The Token. + */ + private String token; + + + /** + * Init device env. + * + * @param urlPath the url path + * @param username the username + * @param password the password + */ + @Override + public void initDeviceEnv(String urlPath, String username, String password) { + this.urlRootPath = urlPath; + this.username = username; + this.password = password; + + upgradeToken(); + } + + /** + * Run dispose mul return type. + * + * @param disposeObject the dispose object + * @param objectType the object type + * @param capType the cap type + * @param nfDirection the nf direction + * @param attackType the attack type + * @param duration the duration + * @return the mul return type + */ + @Override + public MulReturnType runDispose(String disposeObject, DisposeObjectType objectType, DisposeCapacityType capType, + @Nullable NetflowDirection nfDirection, @Nullable Integer attackType, @Nullable Long duration) { + //调用创建安全策略规则的接口 + + String name = "/vsys=public/static-policy/rule=" + getPolicyName(disposeObject); + String url = urlRootPath + name; + String disposeObj = null; + + IPAddress addr = new IPAddressString(disposeObject).getAddress(); + if (addr.isIPv4()) { + disposeObj = disposeObject + "/32"; + } + + if (token == null || token.length() == 0) { + return new MulReturnType<>(ErrorCode.ERR_LOGOUT, ""); + } + + SourceIp sourceIp = new SourceIp(); + sourceIp.setAddressIpv4(disposeObj); + + HuaWeiFireWallCreatePolicyReq policyReq = HuaWeiFireWallCreatePolicyReq.builder() + .sourceIp(sourceIp).action(false).build(); + + try { + log.info("++++Begging HuaWei FireWall Start Cleanup Task: {}", disposeObject); + + //华为防火墙目前只提供封堵功能 + if (capType != DisposeCapacityType.BLACKHOOL) { + log.error("----Error HuaWei FireWall don't support dispose capacity type: {}", capType); + return new MulReturnType<>(ErrorCode.ERR_UNSUPPORT, null); + } + + ErrorCode resp = restfulInterface.createSecurityPolicy(url, token, policyReq); + + // 判断是否token过期 + if (resp == ErrorCode.ERR_TOKENNOTFOUND) { + // 重新登录获取 token + upgradeToken(); + resp = restfulInterface.createSecurityPolicy(url, token, policyReq); + } + + if (resp == null) { + log.error("----Error HuaWei FireWall start clean {} server return error", disposeObject); + return new MulReturnType<>(ErrorCode.ERR_HUAWEIFIREWALL_ERROR, null); + } + + if (resp != ErrorCode.ERR_OK) { + log.error("----Error HuaWei FireWall start clean {} return error: {}, {}", disposeObject, + resp.getCode(), resp.getMsg()); + return new MulReturnType<>(ErrorCode.ERR_HUAWEIFIREWALL_ERROR, null); + } + + log.info("----Finish HuaWei FireWall Start Cleanup Task: {}", disposeObject); + return new MulReturnType<>(ErrorCode.ERR_OK, null); + } catch (Exception ex) { + log.error("----Exception HuaWei FireWall Start Cleanup Task [{}]: {}, {}, {}, {}, {}", ex.getMessage(), + disposeObject, + nfDirection, + duration, url, token); + return new MulReturnType<>(ErrorCode.ERR_SYSTEMEXCEPTION, null); + } + } + + /** + * Stop dispose mul return type. + * + * @param disposeObject the dispose object + * @param capType the cap type + * @param nfDirection the nf direction + * @param attackType the attack type + * @param taskId the task id + * @return the mul return type + */ + @Override + public MulReturnType stopDispose(String disposeObject, DisposeCapacityType capType, + @Nullable NetflowDirection nfDirection, @Nullable Integer attackType, @Nullable String taskId) { + //调用删除安全策略规则的接口,规则名称通过前缀和IP地址进行拼接 + String name = "/vsys=public/static-policy/rule=" + getPolicyName(disposeObject); + String url = urlRootPath + name; + + if (token == null || token.length() == 0) { + return new MulReturnType<>(ErrorCode.ERR_LOGOUT, null); + } + + try { + log.info("++++Begging HuaWei FireWall Stop Cleanup Task: {}", taskId); + + //华为防火墙目前只提供封堵功能 + if (capType != DisposeCapacityType.BLACKHOOL) { + log.error("----Error HuaWei FireWall don't support dispose capacity type: {}", capType); + return new MulReturnType<>(ErrorCode.ERR_UNSUPPORT, null); + } + + if (taskId == null) { + return new MulReturnType<>(ErrorCode.ERR_PARAMS, null); + } + + ErrorCode rspInfo = restfulInterface.deleteSecurityPolicy(url, token); + + // 判断是否token过期 + if (rspInfo == ErrorCode.ERR_TOKENNOTFOUND) { + // 重新登录获取 token + upgradeToken(); + rspInfo = restfulInterface.deleteSecurityPolicy(url, token); + } + + if (rspInfo == null) { + log.error("----Error HuaWei FireWall stop task{} server return error", taskId); + return new MulReturnType<>(ErrorCode.ERR_HUAWEIFIREWALL_ERROR, null); + } + + if (rspInfo != ErrorCode.ERR_OK) { + log.error("----Error HuaWei FireWall stop task{} server return error", taskId); + return new MulReturnType<>(ErrorCode.ERR_HUAWEIFIREWALL_ERROR, null); + } + + log.info("----Finish HuaWei FireWall Stop Cleanup Task: {}", taskId); + return new MulReturnType<>(ErrorCode.ERR_OK, null); + } catch (Exception ex) { + log.error("----Exception HuaWei FireWall Stop Cleanup Task [{}]: {}, {}, {}, {}", ex.getMessage(), + disposeObject, + nfDirection, url, token); + return new MulReturnType<>(ErrorCode.ERR_SYSTEMEXCEPTION, null); + } + } + + /** + * Task status mul return type. + * + * @param taskId the task id + * @return the mul return type + */ + @Override + public MulReturnType taskStatus(String taskId) { + return null; + } + + /** + * Gets ability device fireware. + * + * @return the ability device fireware. + */ + @Override + public MulReturnType getAbilityDeviceFireware() { + return new MulReturnType<>(ErrorCode.ERR_OK, + DeviceFirewareInfo.builder() + .vendor("HuaWeiFireWall") + .model("Unknown") + .firmware("Unknown") + .os("Linux Server") + .kernel("Linux") + .arch("x86_64") + .version("Unknown") + .memory(-1) + .freeMemory(-1) + .cpuUsed(-1) + .build()); + } + + /** + * To device attack type long. + * + * @param ddosAttackTypeMask the ddos attack type mask + * @return the long + */ + @Override + public Long toDeviceAttackType(Long ddosAttackTypeMask) { + return ddosAttackTypeMask; + } + + /** + * Gets device link status. + * + * @return the device link status + */ + @Override + public boolean getDeviceLinkStatus() { + return deviceLinkStatus; + } + + /** + * Dev get link status. + */ + private void devGetLinkStatus() { + try { + //调用华为防火墙查询所有安全策略规则接口,调用成功则认为设备心跳正常 + String url = urlRootPath; + + if (token == null || token.length() == 0) { + deviceLinkStatus = false; + return; + } + + HttpResponse response = restfulInterface.getAllSecurityPolicy(url, token); + + if (response.getStatus() == HttpServletResponse.SC_PRECONDITION_FAILED) { + // 重新登录获取 token + upgradeToken(); + response = restfulInterface.getAllSecurityPolicy(url, token); + } + + if (response.getStatus() == HttpServletResponse.SC_OK) { + deviceLinkStatus = true; + } + + return; + } catch (Exception ex) { + log.error(ex.getMessage()); + } + + deviceLinkStatus = false; + } + + /** + * Gets dispose device protect object. + */ + @Override + public void getDisposeDeviceProtectObject() { + } + + /** + * Is carry protect ip boolean. + * + * @param ipAddr the ip addr + * @return the boolean + */ + @Override + public boolean isCarryProtectIp(String ipAddr) { + return true; + } + + + /** + * Is carry attack type boolean. + * + * @param attackType the attack type + * @return the boolean + */ + @Override + public boolean isCarryAttackType(Long attackType) { + return true; + } + + /** + * Period task runtime. + */ + @Override + public void periodTaskRuntime() { + log.debug("++++HuaWei FireWall Period Task Running"); + + // 更新心跳状态 + if (timerCnt++ % DisposeConfigValue.HEART_PERIOD_OF_SECOND == 0) { + devGetLinkStatus(); + } + + log.debug("----HuaWei FireWall Period Task Running"); + } + + /** + * Device ready boolean. + * + * @return the boolean + */ + @Override + public boolean deviceReady() { + return true; + } + + /** + * Upgrade service group. + * + * @param svrList the svr list + */ + @Override + public void upgradeServiceGroup(List svrList) { + + } + + /** + * Upgrade token. + */ + private void upgradeToken() { + try { + //由用户名密码的base64计算得到,用户名密码格式:用户名:密码 + String plainText = username + ":" + password; + this.token = CryptoHelper.base64Encryption(plainText.getBytes(StandardCharsets.UTF_8)); + } catch (Exception ignored) { + } + } + + /** + * Gets policy name. + * + * @param sourceIp the source Ip + * @return the policy name + */ + private String getPolicyName(String sourceIp) { + return POLICY_NAME_PREFIX + sourceIp; + } +} diff --git a/src/main/java/com/dispose/common/ConstValue.java b/src/main/java/com/dispose/common/ConstValue.java index 6457e992..06eb1037 100644 --- a/src/main/java/com/dispose/common/ConstValue.java +++ b/src/main/java/com/dispose/common/ConstValue.java @@ -11,73 +11,77 @@ public class ConstValue { * The constant STRING_HTTP_AUTH_HEAD. */ public static final String STRING_HTTP_AUTH_HEAD = "Bearer "; + /** + * The constant HUAWEI_FIREWALL_HTTP_AUTH_HEAD. + */ + public static final String HUAWEI_FIREWALL_HTTP_AUTH_HEAD = "Basic "; /** * The constant IP_ADDR_REG. */ public static final String IP_ADDR_REG = "^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}" + - "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^" + - "([\\da-fA-F]{1,4}:){6}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^::" + - "([\\da-fA-F]{1,4}:){0,4}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^" + - "([\\da-fA-F]{1,4}:):([\\da-fA-F]{1,4}:){0,3}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}" + - "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^([\\da-fA-F]{1,4}:){2}:([\\da-fA-F]{1,4}:){0,2}(" + - "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^([\\da-fA-F]{1,4}:){3}:" + - "([\\da-fA-F]{1,4}:){0,1}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^" + - "([\\da-fA-F]{1,4}:){4}:((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^" + - "([\\da-fA-F]{1,4}:){7}[\\da-fA-F]{1,4}$|^:((:[\\da-fA-F]{1,4}){1,6}|:)$|^[\\da-fA-F]{1,4}:((:[\\da-fA-F]{1," + - "4}){1,5}|:)$|^([\\da-fA-F]{1,4}:){2}((:[\\da-fA-F]{1,4}){1,4}|:)$|^([\\da-fA-F]{1,4}:){3}((:[\\da-fA-F]{1," + - "4}){1,3}|:)$|^([\\da-fA-F]{1,4}:){4}((:[\\da-fA-F]{1,4}){1,2}|:)$|^([\\da-fA-F]{1,4}:){5}:([\\da-fA-F]{1,4})" + - "?$|^([\\da-fA-F]{1,4}:){6}:$"; + "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^" + + "([\\da-fA-F]{1,4}:){6}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^::" + + "([\\da-fA-F]{1,4}:){0,4}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^" + + "([\\da-fA-F]{1,4}:):([\\da-fA-F]{1,4}:){0,3}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}" + + "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^([\\da-fA-F]{1,4}:){2}:([\\da-fA-F]{1,4}:){0,2}(" + + "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^([\\da-fA-F]{1,4}:){3}:" + + "([\\da-fA-F]{1,4}:){0,1}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^" + + "([\\da-fA-F]{1,4}:){4}:((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^" + + "([\\da-fA-F]{1,4}:){7}[\\da-fA-F]{1,4}$|^:((:[\\da-fA-F]{1,4}){1,6}|:)$|^[\\da-fA-F]{1,4}:((:[\\da-fA-F]{1," + + "4}){1,5}|:)$|^([\\da-fA-F]{1,4}:){2}((:[\\da-fA-F]{1,4}){1,4}|:)$|^([\\da-fA-F]{1,4}:){3}((:[\\da-fA-F]{1," + + "4}){1,3}|:)$|^([\\da-fA-F]{1,4}:){4}((:[\\da-fA-F]{1,4}){1,2}|:)$|^([\\da-fA-F]{1,4}:){5}:([\\da-fA-F]{1,4})" + + "?$|^([\\da-fA-F]{1,4}:){6}:$"; /** * The constant IP_ADDR_SEGMENT_REG. */ private static final String IP_ADDR_SEGMENT_REG = "^(((((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}" + - "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))-(((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))" + - ")|(((([\\da-fA-F]{1,4}:){6}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(::" + - "([\\da-fA-F]{1,4}:){0,4}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(" + - "([\\da-fA-F]{1,4}:):([\\da-fA-F]{1,4}:){0,3}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}" + - "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(([\\da-fA-F]{1,4}:){2}:([\\da-fA-F]{1,4}:){0,2}(" + - "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(([\\da-fA-F]{1,4}:){3}:" + - "([\\da-fA-F]{1,4}:){0,1}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(" + - "([\\da-fA-F]{1,4}:){4}:((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(" + - "([\\da-fA-F]{1,4}:){7}[\\da-fA-F]{1,4})|(:((:[\\da-fA-F]{1,4}){1,6}|:))|([\\da-fA-F]{1,4}:((:[\\da-fA-F]{1," + - "4}){1,5}|:))|(([\\da-fA-F]{1,4}:){2}((:[\\da-fA-F]{1,4}){1,4}|:))|(([\\da-fA-F]{1,4}:){3}((:[\\da-fA-F]{1," + - "4}){1,3}|:))|(([\\da-fA-F]{1,4}:){4}((:[\\da-fA-F]{1,4}){1,2}|:))|(([\\da-fA-F]{1,4}:){5}:([\\da-fA-F]{1,4})" + - "?)|(([\\da-fA-F]{1,4}:){6}:))-((([\\da-fA-F]{1,4}:){6}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}" + - "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(::([\\da-fA-F]{1,4}:){0,4}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}" + - "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(([\\da-fA-F]{1,4}:):([\\da-fA-F]{1,4}:){0,3}(" + - "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(([\\da-fA-F]{1,4}:){2}:" + - "([\\da-fA-F]{1,4}:){0,2}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(" + - "([\\da-fA-F]{1,4}:){3}:([\\da-fA-F]{1,4}:){0,1}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}" + - "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(([\\da-fA-F]{1,4}:){4}:((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}" + - "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(([\\da-fA-F]{1,4}:){7}[\\da-fA-F]{1,4})|(:((:[\\da-fA-F]{1,4}){1,6}|:))|" + - "([\\da-fA-F]{1,4}:((:[\\da-fA-F]{1,4}){1,5}|:))|(([\\da-fA-F]{1,4}:){2}((:[\\da-fA-F]{1,4}){1,4}|:))|(" + - "([\\da-fA-F]{1,4}:){3}((:[\\da-fA-F]{1,4}){1,3}|:))|(([\\da-fA-F]{1,4}:){4}((:[\\da-fA-F]{1,4}){1,2}|:))|(" + - "([\\da-fA-F]{1,4}:){5}:([\\da-fA-F]{1,4})?)|(([\\da-fA-F]{1,4}:){6}:)))|(((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\" + - ".){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(\\/(\\d|[1-2]\\d|3[0-2]))?)|((([\\da-fA-F]{1,4}:){6}(" + - "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))" + - "?)|(::([\\da-fA-F]{1,4}:){0,4}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(\\/" + - "([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)|(([\\da-fA-F]{1,4}:):([\\da-fA-F]{1,4}:){0,3}(" + - "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))" + - "?)|(([\\da-fA-F]{1,4}:){2}:([\\da-fA-F]{1,4}:){0,2}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}" + - "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)|(([\\da-fA-F]{1,4}:){3}:" + - "([\\da-fA-F]{1,4}:){0,1}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(\\/" + - "([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)|(([\\da-fA-F]{1,4}:){4}:((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}" + - "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)|(([\\da-fA-F]{1,4}:)" + - "{7}[\\da-fA-F]{1,4}(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)|(:((:[\\da-fA-F]{1,4}){1,6}|:)(\\/([1-9]?\\d|(1" + - "([0-1]\\d|2[0-8]))))?)|([\\da-fA-F]{1,4}:((:[\\da-fA-F]{1,4}){1,5}|:)(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)" + - "|(([\\da-fA-F]{1,4}:){2}((:[\\da-fA-F]{1,4}){1,4}|:)(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)|(([\\da-fA-F]{1," + - "4}:){3}((:[\\da-fA-F]{1,4}){1,3}|:)(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)|(([\\da-fA-F]{1,4}:){4}(" + - "(:[\\da-fA-F]{1,4}){1,2}|:)(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)|(([\\da-fA-F]{1,4}:){5}:([\\da-fA-F]{1," + - "4})?(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)|(([\\da-fA-F]{1,4}:){6}:(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?))" + - ")$"; + "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))-(((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))" + + ")|(((([\\da-fA-F]{1,4}:){6}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(::" + + "([\\da-fA-F]{1,4}:){0,4}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(" + + "([\\da-fA-F]{1,4}:):([\\da-fA-F]{1,4}:){0,3}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}" + + "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(([\\da-fA-F]{1,4}:){2}:([\\da-fA-F]{1,4}:){0,2}(" + + "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(([\\da-fA-F]{1,4}:){3}:" + + "([\\da-fA-F]{1,4}:){0,1}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(" + + "([\\da-fA-F]{1,4}:){4}:((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(" + + "([\\da-fA-F]{1,4}:){7}[\\da-fA-F]{1,4})|(:((:[\\da-fA-F]{1,4}){1,6}|:))|([\\da-fA-F]{1,4}:((:[\\da-fA-F]{1," + + "4}){1,5}|:))|(([\\da-fA-F]{1,4}:){2}((:[\\da-fA-F]{1,4}){1,4}|:))|(([\\da-fA-F]{1,4}:){3}((:[\\da-fA-F]{1," + + "4}){1,3}|:))|(([\\da-fA-F]{1,4}:){4}((:[\\da-fA-F]{1,4}){1,2}|:))|(([\\da-fA-F]{1,4}:){5}:([\\da-fA-F]{1,4})" + + "?)|(([\\da-fA-F]{1,4}:){6}:))-((([\\da-fA-F]{1,4}:){6}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}" + + "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(::([\\da-fA-F]{1,4}:){0,4}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}" + + "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(([\\da-fA-F]{1,4}:):([\\da-fA-F]{1,4}:){0,3}(" + + "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(([\\da-fA-F]{1,4}:){2}:" + + "([\\da-fA-F]{1,4}:){0,2}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(" + + "([\\da-fA-F]{1,4}:){3}:([\\da-fA-F]{1,4}:){0,1}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}" + + "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(([\\da-fA-F]{1,4}:){4}:((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}" + + "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?))|(([\\da-fA-F]{1,4}:){7}[\\da-fA-F]{1,4})|(:((:[\\da-fA-F]{1,4}){1,6}|:))|" + + "([\\da-fA-F]{1,4}:((:[\\da-fA-F]{1,4}){1,5}|:))|(([\\da-fA-F]{1,4}:){2}((:[\\da-fA-F]{1,4}){1,4}|:))|(" + + "([\\da-fA-F]{1,4}:){3}((:[\\da-fA-F]{1,4}){1,3}|:))|(([\\da-fA-F]{1,4}:){4}((:[\\da-fA-F]{1,4}){1,2}|:))|(" + + "([\\da-fA-F]{1,4}:){5}:([\\da-fA-F]{1,4})?)|(([\\da-fA-F]{1,4}:){6}:)))|(((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\" + + ".){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(\\/(\\d|[1-2]\\d|3[0-2]))?)|((([\\da-fA-F]{1,4}:){6}(" + + "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))" + + "?)|(::([\\da-fA-F]{1,4}:){0,4}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(\\/" + + "([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)|(([\\da-fA-F]{1,4}:):([\\da-fA-F]{1,4}:){0,3}(" + + "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))" + + "?)|(([\\da-fA-F]{1,4}:){2}:([\\da-fA-F]{1,4}:){0,2}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}" + + "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)|(([\\da-fA-F]{1,4}:){3}:" + + "([\\da-fA-F]{1,4}:){0,1}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(\\/" + + "([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)|(([\\da-fA-F]{1,4}:){4}:((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}" + + "(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)|(([\\da-fA-F]{1,4}:)" + + "{7}[\\da-fA-F]{1,4}(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)|(:((:[\\da-fA-F]{1,4}){1,6}|:)(\\/([1-9]?\\d|(1" + + "([0-1]\\d|2[0-8]))))?)|([\\da-fA-F]{1,4}:((:[\\da-fA-F]{1,4}){1,5}|:)(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)" + + "|(([\\da-fA-F]{1,4}:){2}((:[\\da-fA-F]{1,4}){1,4}|:)(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)|(([\\da-fA-F]{1," + + "4}:){3}((:[\\da-fA-F]{1,4}){1,3}|:)(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)|(([\\da-fA-F]{1,4}:){4}(" + + "(:[\\da-fA-F]{1,4}){1,2}|:)(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)|(([\\da-fA-F]{1,4}:){5}:([\\da-fA-F]{1," + + "4})?(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?)|(([\\da-fA-F]{1,4}:){6}:(\\/([1-9]?\\d|(1([0-1]\\d|2[0-8]))))?))" + + ")$"; /** * The constant IP_PORT_REG. */ public static final String IP_PORT_REG = "^[1-9]$|(^[1-9][0-9]$)|(^[1-9][0-9][0-9]$)|(^[1-9][0-9][0-9][0-9]$)|" + - "(^[1-6][0-5][0-5][0-3][0-5]$)"; + "(^[1-6][0-5][0-5][0-3][0-5]$)"; /** * The constant BUSINESS_TYPE. @@ -92,7 +96,7 @@ public class ConstValue { /** * The constant IP_SEGMENT_SPILT. */ - public static final String[] IP_SEGMENT_SPILT = new String[] {"-", "/"}; + public static final String[] IP_SEGMENT_SPILT = new String[]{"-", "/"}; /** * The constant IPV6_ERR_SEGMENT_SPILT. diff --git a/src/main/java/com/dispose/common/DisposeDeviceType.java b/src/main/java/com/dispose/common/DisposeDeviceType.java index 7a93db61..a2b79ad8 100644 --- a/src/main/java/com/dispose/common/DisposeDeviceType.java +++ b/src/main/java/com/dispose/common/DisposeDeviceType.java @@ -26,6 +26,10 @@ public enum DisposeDeviceType implements BaseEnum { * Dptech bypass umc dispose device type. */ DPTECH_BYPASS_UMC(4, "迪普旁路牵引UMC管理平台"), + /** + * The Huawei FireWall platform. + */ + HUAWEI_FIREWALL_PLATFORM(5, "华为防火墙"), /** * The Virtual dispose. */ diff --git a/src/main/java/com/dispose/common/ErrorCode.java b/src/main/java/com/dispose/common/ErrorCode.java index 83c949a4..0cba359e 100644 --- a/src/main/java/com/dispose/common/ErrorCode.java +++ b/src/main/java/com/dispose/common/ErrorCode.java @@ -286,6 +286,10 @@ public enum ErrorCode { * Err not found device error code. */ ERR_NOTFOUNDDEVICE(304, "找不到设备先添加设备"), + /** + * The Err huawei firewall error. + */ + ERR_HUAWEIFIREWALL_ERROR(305, "华为防火墙返回错误"), ; /** diff --git a/src/main/java/com/dispose/restful/RestfulInterface.java b/src/main/java/com/dispose/restful/RestfulInterface.java index 7804c713..ef89344e 100644 --- a/src/main/java/com/dispose/restful/RestfulInterface.java +++ b/src/main/java/com/dispose/restful/RestfulInterface.java @@ -102,6 +102,43 @@ public class RestfulInterface { .execute(); } + /** + * Gets json. + * + * @param url the url + * @param header the header + * @return the http response + */ + private static HttpResponse huaweiFireWallGetJson(String url, Map header) { + HttpRequest.setGlobalTimeout(timeOutValue); + return HttpRequest.get(url).addHeaders(header).execute(); + } + + /** + * Post json. + * + * @param url the url + * @param header the header + * @param body the body + * @return the http response + */ + private static HttpResponse huaweiFireWallPostJson(String url, Map header, String body) { + HttpRequest.setGlobalTimeout(timeOutValue); + return HttpRequest.post(url).addHeaders(header).body(body).execute(); + } + + /** + * Deletes http response. + * + * @param url the url + * @param header the header + * @return the http response + */ + private static HttpResponse huaweiFireWallDeleteJson(String url, Map header, String body) { + HttpRequest.setGlobalTimeout(timeOutValue); + return HttpRequest.delete(url).addHeaders(header).body(body).execute(); + } + /** * Protocol run t. * @@ -187,12 +224,12 @@ public class RestfulInterface { log.debug("Restful response: {}, {}: {}", url, token, svrResp); return OBJECT_MAPPER.readValue(svrResp, - new TypeReference>() { - @Override - public Type getType() { - return createRespType(subClass); - } - }); + new TypeReference>() { + @Override + public Type getType() { + return createRespType(subClass); + } + }); } catch (JsonProcessingException e) { log.debug("System exception: ", e); return null; @@ -258,6 +295,63 @@ public class RestfulInterface { } } + /** + * huawei firewall pro run protocol resp dto. + * + * @param url the url + * @param token the token + * @param reqBody the obj + * @param reqType the req type + * @return the t + */ + public static HttpResponse huaWeiFireWallProRun(String url, String token, String reqBody, RequestMethod reqType) { + String body = ""; + HttpResponse svrResp = null; + + //HTTP请求头格式 + Map httpHeadMap = new HashMap<>(2); + httpHeadMap.put(String.valueOf(Header.CONNECTION), "keep-alive"); + httpHeadMap.put(String.valueOf(Header.ACCEPT), "application/yang.operation+xml"); + + if (token != null && token.length() > 0) { + httpHeadMap.put(String.valueOf(Header.AUTHORIZATION), ConstValue.HUAWEI_FIREWALL_HTTP_AUTH_HEAD + token); + } + + //实际数据长度,没有数据部分时,值为0。 + httpHeadMap.put(String.valueOf(Header.CONTENT_LENGTH), body.equals(reqBody) ? String.valueOf(0) : String.valueOf(reqBody.length())); + + //HTTP请求提交的内容类型,只有在POST方法提交时才需要设置此属性 && body内容为空时,该字段可不存在或取值为空 + if ((!body.equals(reqBody)) && RequestMethod.POST.equals(reqType)) { + httpHeadMap.put(String.valueOf(Header.CONTENT_TYPE), "application/yang.operation+xml"); + } + + log.debug("Restful request: {}, {}: {}", url, token, reqBody); + + switch (reqType) { + case GET: + svrResp = huaweiFireWallGetJson(url, httpHeadMap); + break; + case POST: + svrResp = huaweiFireWallPostJson(url, httpHeadMap, reqBody); + break; + case DELETE: + svrResp = huaweiFireWallDeleteJson(url, httpHeadMap, reqBody); + break; + default: + log.error("Unknown method: {}", reqType); + break; + } + + if (svrResp == null) { + log.debug("Server return null: {}", url); + return null; + } + + log.debug("Restful response: {}, {}: {}", url, token, svrResp.body()); + + return svrResp; + } + /** * Create resp type type. * @@ -269,6 +363,6 @@ public class RestfulInterface { Type[] types = new Type[1]; types[0] = c; return ParameterizedTypeImpl.make(ProtocolRespDTO.class, types, - ProtocolRespDTO.class.getDeclaringClass()); + ProtocolRespDTO.class.getDeclaringClass()); } } diff --git a/src/main/java/com/dispose/service/impl/DeviceTaskManagerServiceImpl.java b/src/main/java/com/dispose/service/impl/DeviceTaskManagerServiceImpl.java index 1ad74576..9d3338a3 100644 --- a/src/main/java/com/dispose/service/impl/DeviceTaskManagerServiceImpl.java +++ b/src/main/java/com/dispose/service/impl/DeviceTaskManagerServiceImpl.java @@ -584,6 +584,10 @@ public class DeviceTaskManagerServiceImpl implements DeviceTaskManagerService { restfulDeviceTaskRun(ai, v, task, DisposeDeviceType.HUAWEI_PLATFORM); break; + case HUAWEI_FIREWALL_PLATFORM: + restfulDeviceTaskRun(ai, v, task, DisposeDeviceType.HUAWEI_FIREWALL_PLATFORM); + break; + default: log.error("Unknown dispose device type: {}", ai.getDev()); break; @@ -661,6 +665,10 @@ public class DeviceTaskManagerServiceImpl implements DeviceTaskManagerService { restfulDeviceTaskStop(ai, v, task, DisposeDeviceType.HUAWEI_PLATFORM); break; + case HUAWEI_FIREWALL_PLATFORM: + restfulDeviceTaskStop(ai, v, task, DisposeDeviceType.HUAWEI_FIREWALL_PLATFORM); + break; + default: log.error("Unknown dispose device type: {}", ai.getDev()); break; diff --git a/src/main/java/com/dispose/service/impl/DisposeAbilityRouterServiceImpl.java b/src/main/java/com/dispose/service/impl/DisposeAbilityRouterServiceImpl.java index 8bf20632..de72ad6c 100644 --- a/src/main/java/com/dispose/service/impl/DisposeAbilityRouterServiceImpl.java +++ b/src/main/java/com/dispose/service/impl/DisposeAbilityRouterServiceImpl.java @@ -5,6 +5,7 @@ import com.dispose.ability.impl.DpTechAbilityImpl; import com.dispose.ability.impl.DpTechBypassAbilityImpl; import com.dispose.ability.impl.HaoHanAbilityImpl; import com.dispose.ability.impl.HuaWeiAbilityImpl; +import com.dispose.ability.impl.HuaWeiFireWallAbilityImpl; import com.dispose.ability.impl.PengXinAbilityImpl; import com.dispose.ability.impl.VirtualAbilityImpl; import com.dispose.common.DisposeCapacityType; @@ -89,7 +90,7 @@ public class DisposeAbilityRouterServiceImpl implements DisposeAbilityRouterServ if (dev != null) { return disposeAbilityMap.get(getAbilityDeviceHashKey(dev.getIpAddr(), dev.getIpPort(), - String.valueOf(dev.getDeviceType()))); + String.valueOf(dev.getDeviceType()))); } return null; @@ -119,7 +120,7 @@ public class DisposeAbilityRouterServiceImpl implements DisposeAbilityRouterServ @Override public void deleteDisposeDevice(DisposeDevice dev) { String hashKey = getAbilityDeviceHashKey(dev.getIpAddr(), dev.getIpPort(), - String.valueOf(dev.getDeviceType())); + String.valueOf(dev.getDeviceType())); disposeAbilityMap.remove(hashKey); } @@ -168,6 +169,9 @@ public class DisposeAbilityRouterServiceImpl implements DisposeAbilityRouterServ db = new DpTechBypassAbilityImpl(); db.upgradeServiceGroup(serviceGroupMapper.selectAll()); break; + case HUAWEI_FIREWALL_PLATFORM: + db = new HuaWeiFireWallAbilityImpl(); + break; default: log.error("Unknown dispose device type: {}", dev.getDeviceType()); return ErrorCode.ERR_PARAMS; @@ -178,7 +182,7 @@ public class DisposeAbilityRouterServiceImpl implements DisposeAbilityRouterServ db.getDisposeDeviceProtectObject(); String hashKey = getAbilityDeviceHashKey(dev.getIpAddr(), dev.getIpPort(), - String.valueOf(dev.getDeviceType())); + String.valueOf(dev.getDeviceType())); // 缓存处置设备到Hash表中 disposeAbilityMap.put(hashKey, AbilityInfo.builder() @@ -240,7 +244,7 @@ public class DisposeAbilityRouterServiceImpl implements DisposeAbilityRouterServ if (dev == null || !dev.getStatus().equals(ObjectStatus.NORMAL)) { String hashKey = getAbilityDeviceHashKey(v.getDev().getIpAddr(), v.getDev().getIpPort(), - String.valueOf(v.getDev().getDeviceType())); + String.valueOf(v.getDev().getDeviceType())); disposeAbilityMap.remove(hashKey); } else { diff --git a/src/main/java/com/huaweifirewall/dispose/common/HuaWeiFireWallCreatePolicyReq.java b/src/main/java/com/huaweifirewall/dispose/common/HuaWeiFireWallCreatePolicyReq.java new file mode 100644 index 00000000..17f00ad7 --- /dev/null +++ b/src/main/java/com/huaweifirewall/dispose/common/HuaWeiFireWallCreatePolicyReq.java @@ -0,0 +1,43 @@ +package com.huaweifirewall.dispose.common; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; +import java.io.Serializable; + +/** + * @author Nicole + */ +@Getter +@Setter +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "rule") +@XmlType(propOrder = { + "sourceIp", + "action", +}) +public class HuaWeiFireWallCreatePolicyReq implements Serializable { + /** + * The rule action. false:block true:unblock + */ + private Boolean action; + /** + * The source Ip. + */ + @XmlElement(name = "source-ip") + private SourceIp sourceIp; + +} diff --git a/src/main/java/com/huaweifirewall/dispose/common/SourceIp.java b/src/main/java/com/huaweifirewall/dispose/common/SourceIp.java new file mode 100644 index 00000000..daa65fed --- /dev/null +++ b/src/main/java/com/huaweifirewall/dispose/common/SourceIp.java @@ -0,0 +1,23 @@ +package com.huaweifirewall.dispose.common; + +import lombok.Getter; +import lombok.Setter; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; + + +/** + * @author Nicole + */ +@Setter +@Getter +@XmlAccessorType(XmlAccessType.FIELD) +public class SourceIp { + /** + * The address ipV4. + */ + @XmlElement(name = "address-ipv4") + private String addressIpv4; +} diff --git a/src/main/java/com/huaweifirewall/dispose/protocol/HuaWeiFireWallInterface.java b/src/main/java/com/huaweifirewall/dispose/protocol/HuaWeiFireWallInterface.java new file mode 100644 index 00000000..729fffee --- /dev/null +++ b/src/main/java/com/huaweifirewall/dispose/protocol/HuaWeiFireWallInterface.java @@ -0,0 +1,135 @@ +package com.huaweifirewall.dispose.protocol; + +import cn.hutool.http.HttpResponse; +import com.dispose.common.ErrorCode; +import com.dispose.restful.RestfulInterface; +import com.huaweifirewall.dispose.common.HuaWeiFireWallCreatePolicyReq; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.RequestMethod; + +import javax.servlet.http.HttpServletResponse; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; +import java.io.StringReader; +import java.io.StringWriter; + +/** + * The type Hua wei FireWall interface. + * + * @author Nicole + */ +@Slf4j +public class HuaWeiFireWallInterface { + + + /** + * Create security policy. + * + * @param baseUrlPath the base url path + * @param token the token + * @param policyReq the policy request + * @return the error code + */ + public ErrorCode createSecurityPolicy(String baseUrlPath, String token, HuaWeiFireWallCreatePolicyReq policyReq) { + //拼接HTTP body部分,xml格式。 + String bodyContent = convertToXml(policyReq); + + //获取HTTP RESPONSE消息 + HttpResponse response = RestfulInterface.huaWeiFireWallProRun(baseUrlPath, + token, + bodyContent, + RequestMethod.POST); + + //对响应内容进行处理 + if (response != null) { + if (response.getStatus() == HttpServletResponse.SC_CREATED) { + return ErrorCode.ERR_OK; + } + } + + log.error("----HuaWei response [{}]: {}", response == null ? -1 : response.getStatus(), response); + return ErrorCode.ERR_UNKNOWNCMD; + } + + /** + * delete security policy. + * + * @param baseUrlPath the base url path + * @param token the token + * @return the error code + */ + public ErrorCode deleteSecurityPolicy(String baseUrlPath, String token) { + HttpResponse response = RestfulInterface.huaWeiFireWallProRun(baseUrlPath, + token, + "", + RequestMethod.DELETE); + + //对响应内容进行处理 + if (response != null) { + if (response.getStatus() == HttpServletResponse.SC_CREATED) { + return ErrorCode.ERR_OK; + } + } + + log.error("----HuaWei response [{}]: {}", response == null ? -1 : response.getStatus(), response); + return ErrorCode.ERR_UNKNOWNCMD; + } + + + /** + * get all security policy. + * + * @param baseUrlPath the base url path + * @param token the token + * @return the error code + */ + public HttpResponse getAllSecurityPolicy(String baseUrlPath, String token) { + return RestfulInterface.huaWeiFireWallProRun(baseUrlPath, + token, + "", + RequestMethod.GET); + } + + /** + * 将对象转成string类型的XML输出 + * + * @return String + */ + public static String convertToXml(Object obj) { + //创建输出流 + StringWriter stringWriter = new StringWriter(); + try { + //jdk转换类实现 + JAXBContext context = JAXBContext.newInstance(obj.getClass()); + Marshaller marshaller = context.createMarshaller(); + //格式化xml输出的格式 + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + //对子昂转换成输出流形式的xml + marshaller.marshal(obj, stringWriter); + } catch (JAXBException e) { + e.printStackTrace(); + } + + return stringWriter.toString(); + } + + /** + * 将string类型的XML转换成对象 + */ + public static Object convertXmlStrToObject(Class clazz, String xmlStr) { + Object xmlObject = null; + try { + JAXBContext context = JAXBContext.newInstance(clazz); + //xml转换成对象 + Unmarshaller unmarshaller = context.createUnmarshaller(); + StringReader sr = new StringReader(xmlStr); + xmlObject = unmarshaller.unmarshal(sr); + } catch (JAXBException e) { + e.printStackTrace(); + } + + return xmlObject; + } +} diff --git a/src/test/java/com/dispose/test/common/HttpBodyXmlTest.java b/src/test/java/com/dispose/test/common/HttpBodyXmlTest.java new file mode 100644 index 00000000..06247028 --- /dev/null +++ b/src/test/java/com/dispose/test/common/HttpBodyXmlTest.java @@ -0,0 +1,139 @@ +package com.dispose.test.common; + + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.huaweifirewall.dispose.common.HuaWeiFireWallCreatePolicyReq; +import com.huaweifirewall.dispose.common.SourceIp; +import lombok.extern.slf4j.Slf4j; +import org.dom4j.Document; +import org.dom4j.DocumentHelper; +import org.dom4j.Element; +import org.dom4j.io.OutputFormat; +import org.dom4j.io.XMLWriter; +import org.junit.Test; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; +import java.io.*; + + +@Slf4j +public class HttpBodyXmlTest { + + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + /** + * 生成xml方法 + */ + public static String createXml(String sourceIp) { + try { + // 1、创建document对象 + Document document = DocumentHelper.createDocument(); + // 2、创建根节点rss + Element rule = document.addElement("rule"); + // 3、生成子节点及子节点内容 + Element desc = rule.addElement("desc"); + desc.setText("just for test"); + Element sourceZone = rule.addElement("source-zone"); + sourceZone.setText("trust"); + Element destinationZone = rule.addElement("destination-zone"); + destinationZone.setText("untrust"); + Element addressIpv4 = rule.addElement("address-ipv4"); + addressIpv4.setText(sourceIp); + // 5、设置生成xml的格式 + OutputFormat format = OutputFormat.createPrettyPrint(); + // 设置编码格式 + format.setEncoding("UTF-8"); + // 6、生成xml文件 + File file = new File("rule.xml"); + XMLWriter writer = new XMLWriter(new FileOutputStream(file), format); + // 设置是否转义,默认使用转义字符 + writer.setEscapeText(false); + writer.write(document); + writer.close(); + System.out.println("生成rss.xml成功"); + return document.asXML(); + + } catch (Exception e) { + e.printStackTrace(); + System.out.println("生成rss.xml失败"); + } + + return null; + } + + + /** + * 将对象转成string类型的XML输出 + * + * @return String + */ + public static String convertToXml(Object obj) { + //创建输出流 + StringWriter stringWriter = new StringWriter(); + try { + //jdk转换类实现 + JAXBContext context = JAXBContext.newInstance(obj.getClass()); + Marshaller marshaller = context.createMarshaller(); + //格式化xml输出的格式 + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + //对子昂转换成输出流形式的xml + marshaller.marshal(obj, stringWriter); + } catch (JAXBException e) { + e.printStackTrace(); + } + + return stringWriter.toString(); + } + + /** + * 将string类型的XML转换成对象 + */ + public static Object convertXmlStrToObject(Class clazz, String xmlStr) { + Object xmlObject = null; + try { + JAXBContext context = JAXBContext.newInstance(clazz); + //xml转换成对象 + Unmarshaller unmarshaller = context.createUnmarshaller(); + StringReader sr = new StringReader(xmlStr); + xmlObject = unmarshaller.unmarshal(sr); + } catch (JAXBException e) { + e.printStackTrace(); + } + + return xmlObject; + } + + @Test + public void objAndXml() { + HuaWeiFireWallCreatePolicyReq policyReq = HuaWeiFireWallCreatePolicyReq.builder() + .action(false) + .build(); + + SourceIp sourceIp = new SourceIp(); + sourceIp.setAddressIpv4("1.1.1.1/32"); + policyReq.setSourceIp(sourceIp); + + log.info("-------------将对象转成string类型的xml--------"); + String str = convertToXml(policyReq); + log.info("-------------str:{}", str); + + log.info("-------------将string类型的xml转成对象--------"); + HuaWeiFireWallCreatePolicyReq req = (HuaWeiFireWallCreatePolicyReq) convertXmlStrToObject(HuaWeiFireWallCreatePolicyReq.class, str); + log.info("-------------sourceIp:{}, action:{}", req.getSourceIp().getAddressIpv4(), req.getAction()); + } + + @Test + public void httpXmlTest() throws JsonProcessingException { + // TODO Auto-generated method stub + String reqJson = OBJECT_MAPPER.writeValueAsString(null); + log.info("reqJson-->{}", reqJson); + + String bodyStr = createXml("1.1.1.1/32"); + log.info("bodyStr-->{}", bodyStr); + + } +}