12.自定义注解、切面-查看文章

12.自定义注解、切面

发表于:2017-06-24 10:36:19 分类:博客源码 阅读:936次

image

这两段代码是百度出来抄的,主要用于页面防JS注入等。作者页就不留了,因为我还得再找。

自定义注解

  1. AntiXSS

package top.ersredma.blog.anotations;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.lang.annotation.*;

/**
 * Created by ersredma on 2017/6/21.
 */
@Component
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)
public @interface AntiXSS {
}

2.切面 AntiXSSAspect 主要是获取参数并调用处理方法。

package top.ersredma.blog.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import top.ersredma.blog.utils.XssShieldUtil;

import java.lang.reflect.Field;
/**
 * Created by ersredma on 2017/6/21.
 * 对String或者Entity中的String进行AntiXSS处理
 */
@Aspect
public class AntiXSSAspect {
    /** * 定义切面,定位到@AntiXSS注解的地方 */
    @Pointcut("@annotation(top.ersredma.blog.anotations.AntiXSS)")
    //@Pointcut(value = "execution(* top.ersredma.blog.service.BlogServiceImpl.addComment(..))")
    public void antiXSSPointCut() { }
    /** * 对String类型或包含String类型的Entity进行antiXSS处理 * * @param point */
    @Around("antiXSSPointCut()")
    public Object doAround(ProceedingJoinPoint point) {
        Object result = null;
        Object args[] = point.getArgs();
        try {
            antiXSS(args);
            result = point.proceed(args);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return result;
    }
    /** * antiXSS处理 * * @param args */
    private void antiXSS(Object[] args) {
        if (args == null) {
            return;
        }
        for (int i = 0; i < args.length; i++) {
            if (args[i] == null) {
                continue;
            }
            if (args[i] instanceof String) {
                args[i] = antiXSS((String) args[i]);
            }
            if (!isPrimitive(args[i])) {
                args[i] = antiXSSEntity(args[i]);
            }
        }
    }
    /** * 对Entity进行antiXSS * * @param object * @return 处理后的结果 */
    private Object antiXSSEntity(Object object) {
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object arg = field.get(object);
                if (arg instanceof String) {
                    arg = antiXSS((String) arg);
                    field.set(object, arg);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return object;
    }
    /** * 判断是否是基本类型 * * @param arg * @return */
    private boolean isPrimitive(Object arg) {
        try {
            /************ 基本类型中包含Class<T> TYPE字段 **********/
            Field field = arg.getClass().getDeclaredField("TYPE");
            field.setAccessible(true);
            Class fieldClass = (Class) field.get(arg);
            if (fieldClass.isPrimitive()) {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }
    /** * antiXSS实现 * * @param target * @return */
    private String antiXSS(String target) {
        return XssShieldUtil.stripXss(target);
    }
}

3.处理类 (作者的代码是简单粗暴的替换,这块还得改,不然没办法支持富文本编辑器)

package top.ersredma.blog.utils;

 import java.util.ArrayList;
        import java.util.List;
        import java.util.regex.Matcher;
        import java.util.regex.Pattern;

/**
 * 处理非法字符
 *
 * @author   单红宇(365384722)
 * @myblog  http://blog.csdn.net/catoop/
 * @create    2015年9月18日
 */
public class XssShieldUtil {

    private static List<Pattern> patterns = null;

    private static List<Object[]> getXssPatternList() {
        List<Object[]> ret = new ArrayList<Object[]>();

        ret.add(new Object[]{"<(no)?script[^>]*>.*?</(no)?script>", Pattern.CASE_INSENSITIVE});
        ret.add(new Object[]{"eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        ret.add(new Object[]{"expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        ret.add(new Object[]{"(javascript:|vbscript:|view-source:)*", Pattern.CASE_INSENSITIVE});
        ret.add(new Object[]{"(<jsp:include|<%>)", Pattern.CASE_INSENSITIVE});
       // ret.add(new Object[]{"<(\"[^\"]*\"|\'[^\']*\'|[^\'\">])*>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        ret.add(new Object[]{"(window\\.location|window\\.|\\.location|document\\.cookie|document\\.|alert\\(.*?\\)|window\\.open\\()*", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        ret.add(new Object[]{"<+\\s*\\w*\\s*(oncontrolselect|oncopy|oncut|ondataavailable|ondatasetchanged|ondatasetcomplete|ondblclick|ondeactivate|ondrag|ondragend|ondragenter|ondragleave|ondragover|ondragstart|ondrop|onerror=|onerroupdate|onfilterchange|onfinish|onfocus|onfocusin|onfocusout|onhelp|onkeydown|onkeypress|onkeyup|onlayoutcomplete|onload|onlosecapture|onmousedown|onmouseenter|onmouseleave|onmousemove|onmousout|onmouseover|onmouseup|onmousewheel|onmove|onmoveend|onmovestart|onabort|onactivate|onafterprint|onafterupdate|onbefore|onbeforeactivate|onbeforecopy|onbeforecut|onbeforedeactivate|onbeforeeditocus|onbeforepaste|onbeforeprint|onbeforeunload|onbeforeupdate|onblur|onbounce|oncellchange|onchange|onclick|oncontextmenu|onpaste|onpropertychange|onreadystatechange|onreset|onresize|onresizend|onresizestart|onrowenter|onrowexit|onrowsdelete|onrowsinserted|onscroll|onselect|onselectionchange|onselectstart|onstart|onstop|onsubmit|onunload)+\\s*=+", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL});
        return ret;
    }

    private static List<Pattern> getPatterns() {

        if (patterns == null) {
            List<Pattern> list = new ArrayList<Pattern>();
            String regex = null;
            Integer flag = null;
            int arrLength = 0;
            for(Object[] arr : getXssPatternList()) {
                arrLength = arr.length;
                for(int i = 0; i < arrLength; i++) {
                    regex = (String)arr[0];
                    flag = (Integer)arr[1];
                    list.add(Pattern.compile(regex, flag));
                }
            }
            patterns = list;
        }

        return patterns;
    }

    public static String stripXss(String value) {
        if(value!=null&&!"".equals(value)) {

            Matcher matcher = null;

            for(Pattern pattern : getPatterns()) {
                matcher = pattern.matcher(value);
                // 匹配
                if(matcher.find()) {
                    // 删除相关字符串
                    value = value.replaceAll(pattern.pattern(),"");
                }
            }
        }

        return value;
    }
    
}


关键词:blog源码,防注入


验证码:

  1. author
    盖运聪(伪装者) 2017-07-08 17:58:08
    厉害了,我只敢想想,做不出来
  2. author
    刘玄处(伪装者) 2017-06-27 16:15:37
  3. author
    余兆兴(伪装者) 2017-06-27 16:15:35
  4. author
    术赤(伪装者) 2017-06-26 10:40:45
    h h h
  5. author
    黎生(伪装者) 2017-06-26 10:40:44
    h h h