JPQL-Injection 和 SQL-Injection 之间有什么区别

What are the differences between a JPQL-Injection and SQL-Injection

我已经阅读了 JPQL 注入和 SQL 注入。在许多网站上,从测试人员的角度来看,ORM 注入几乎与 SQL 注入相同。所以基本上我想知道的是 JPQL 和 SQL 注入之间的主要区别。

JPQL 注入和 SQL 注入都是 Code Injection 更广泛类别的示例。

任何在运行时解析的 语言都容易受到代码注入的影响。

JPQL 或 Java Persistence Query Language 在语法上与 SQL 相似,事实上它被写成字符串并在运行时解析。

Building queries by passing JPQL query strings directly to the createQuery method, as shown above, is referred to in JPA as dynamic query construction because the query string can be built dynamically at runtime.

当描述说 "built dynamically at runtime" 时,它们意味着您的代码将 JPQL 查询格式化为 Java 字符串,然后提交要解析和执行的字符串。因此,您的代码有机会结合固定字符串和可变内容。

下面是安全使用参数将变量与 JPQL 语句组合的示例。这来自https://www.objectdb.com/java/jpa/query/parameter

安全:

TypedQuery<Country> query = em.createQuery(
    "SELECT c FROM Country c WHERE c.name = :name", Country.class);
return query.setParameter("name", name).getSingleResult();

这是以不安全方式编写的相同查询,将变量直接组合到字符串中。

不安全:

TypedQuery<Country> query = em.createQuery(
    "SELECT c FROM Country c WHERE c.name = '" + name + "'", Country.class);

如果可以避免,请不要使用字符串连接来形成 JPQL 查询。这就是不安全内容潜入您的 JPQL 的方式。