hibernate规避SQL注入实例

  项目被检测出SQL注入,注入url如:http://127.0.0.1:8080/Test/wlf/getServiceInfo.html?province=%25E6%25B5%2599%25E6%25B1%259F50760358&timeType=1

  利用常用SQL注入工具可获取数据库详细情况如下所示:

  sqlmap命令

  注入漏洞信息:

  针对SQL注入漏洞,一般的应对方式是在服务器端加强HTTP请求字符过滤,防范注入攻击,但这里是用hibernate作为ORM操作数据库,更为彻底的方式是参数的处理。先看原来的查询操作:

    public List<ProvinceListVO> getServiceInfo(String province,String timeType) {
        List<ProvinceListVO> listVO = new ArrayList<ProvinceListVO>();
        StringBuffer sb =new StringBuffer();
        sb.append("select * from v_wlf_info t  where t.province='")
        .append(province).append("' and time_type='").append(timeType).append("'")
        .append(" and t.total>0");
        try {
            listVO = this.queryByJdbcForBean2(sb.toString(), ProvinceListVO.class);
        } catch (Exception e) {
            
            e.printStackTrace();
        }
        return listVO;
    }

  问题就出在标红那一行,明明是两个参数,非得搞成字符串,让人家有机可乘。修改后的代码:

    public List<ProvinceListVO> getServiceInfo(String province,String timeType) {
        List<ProvinceListVO> listVO = new ArrayList<ProvinceListVO>();
        StringBuffer sb =new StringBuffer();
        sb.append("select * from v_wlf_info t  where t.province=? and t.time_type=?")
//        .append(province).append("' and time_type='").append(timeType).append("'")
        .append(" and t.total>0");
        try {
            listVO = this.queryByJdbcForBean2(sb.toString(), ProvinceListVO.class, province, timeType);
        } catch (Exception e) {
            
            e.printStackTrace();
        }
        return listVO;
    }

  我们看下queryByJdbcForBean2干了啥:

    public <T> List<T> queryByJdbcForBean2(String sql,Class c,final Object... values){   
        List<T> list= new ArrayList<T>();
        Session session = null;
        try {
             session = this.getSession();
            Query query = this.getSession().createSQLQuery(sql);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    query.setParameter(i, values[i]);
                }
            }
            List<Object> rlist = query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
            
            for (Object object : rlist) {
                Map map = (Map) object;
                T t = (T) Map2BeanUtils.map2Bean(map, c, Map2BeanUtils.DB_COLUMN_TYPE);
                list.add(t);
            } 
        } catch (DataAccessResourceFailureException e) {
            e.printStackTrace();
        } catch (HibernateException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }finally{

            if(session != null)
                this.releaseSession(session);

        }
        return list;
    }

  上面使用的是利用setParameter方法来防止在参数上做手脚。

猜你喜欢

转载自www.cnblogs.com/wuxun1997/p/10133010.html