如何解决SQL Injection Veracode问题-CWE 564

问题描述

@Override
public AssetLibraryReference selectALRefByName(String entityName,String name) throws Exception {
    AssetLibraryReference returnRef = null;
    String query = "from " + entityName + " where name = :name ";
    
    try {
        returnRef = sessionQueryUtil.doSessionQuery(session -> {
        //  queryStr.append("from " + entityName + " where name = :name ");             
            
          Query q =  session.createQuery(query);
                  q.setString("name",name);    
            
            
            return (AssetLibraryReference)q.uniqueResult();
        });
    } catch (HibernateException e) {
        LOG.error ("Caught hibernate exception",e);
        e.printStackTrace();
        throw e;
    } catch (Exception e) {
        LOG.error("Caught Exception :"+e.getMessage());
        e.printStackTrace();
        throw e;
    }

    return returnRef;
}

我在Query q = session.createQuery(query);遇到Veracode扫描错误。谁能帮我解决这个问题。我在这里可以用来解决此问题。 veracode的问题ID是CWE 564。

解决方法

改为使用query.setParameter命名,以防止SQL注入

@Override
public AssetLibraryReference selectALRefByName(String entityName,String name) throws Exception {
    AssetLibraryReference returnRef = null;
    String query = "from " + entityName + " where name = :name ";
    
    try {
        returnRef = sessionQueryUtil.doSessionQuery(session -> {
        //  queryStr.append("from " + entityName + " where name = :name ");             
            
          Query q =  session.createQuery(query);
                  q.setParameter("name",name);    
            
            
            return (AssetLibraryReference)q.uniqueResult();
        });
    } catch (HibernateException e) {
        LOG.error ("Caught hibernate exception",e);
        e.printStackTrace();
        throw e;
    } catch (Exception e) {
        LOG.error("Caught Exception :"+e.getMessage());
        e.printStackTrace();
        throw e;
    }

    return returnRef;
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...