The post has been translated automatically. Original language: Russian
On December 2, the Django team released corrective releases 6.1.4, 6.0.11 and 5.2.20. They close seven vulnerabilities: two with a high level of danger, one medium and four low. The fixes are in all supported branches.: 6.1, 6.0, 5.2 and main. In addition, branch 6.1 received seven common bugfixes, including regressions from the previous release.
Two high-risk vulnerabilities
The first concerns GeoDjango and PostGIS. The RasterField field allowed writing a file to an arbitrary location on the server using a custom name and a non-standard GDAL driver, which potentially opens the way to code execution. The field could be accessed normally: through a spare CharField in the forms, that is, through the admin panel, ModelForm, and serializers with a record. Now RasterField is not editable by default (editable is set to False). A dictionary or a JSON string with a non-standard driver causes a GDALException, and the other driver must be explicitly wrapped in GDALRaster, marking the description as trusted. The developers warn that with untrusted input, there remains a risk of SSRF. The defect does not affect the geometry fields.
The second vulnerability is a possible SQL injection into ORM lookups range and in. It was opened by percentage signs in aliases and in key transformations. Range required more than two values on the right side, while in required a two—sided transform. Now range takes exactly two values. Percentages in aliases and key transformations were deprecated back in 6.0, and their support will be removed in 2028.
Medium and low
- XSS in the truncatechars_html filter and in the Truncator.chars method with the html flag: triggered when the length of the text matched the length of the crop, and the result was output to the HTML attribute.
- Cache poisoning: build_absolute_uri mistakenly normalized path segments with a dot and two dots. With some deployment schemes, an anonymous user could cause UpdateCacheMiddleware and cache_page to send a cached response to the wrong address. Such segments are now saved.
- Two data leaks in the list of admin panel objects: an employee with the right to view only could sort through the values through the alias pk of a model with its own OneToOneField primary key (by default, these are models with multi-tabular inheritance) and through repeated lookups via feedback. The second problem is regression, which appeared in 5.0.3.
- Heap buffer overflow in OGRGeometry.wkb: On 64-bit platforms, too small a buffer was allocated for geometries larger than 4 GB. hex, geos, and pickle are also affected.
What else is fixed in 6.1.4
Branch 6.1 received regression fixes: executemany crashes on Oracle when only part of the string parameters are longer than 4000 characters; union, intersection, and difference crashes when sorting the model by related fields; incorrect negation of nullable-BooleanField via ~F on SQLite. Added compatibility with pylibmc 1.8.0, and FETCH_PEERS mode no longer returns None instead of ObjectDoesNotExist for a deleted linked object.
What does this mean in practice?
It's worth updating right away, especially projects on GeoDjango and PostGIS. If RasterField is edited somewhere via forms or API, the field will disappear from ModelForm after the update, and this may break the raster loading scripts. Check them with tests and, if necessary, explicitly allow the field, but with driver verification.
By searching through the code, find range calls with a variable list of values: if more than two elements once got there, now it's an error. At the same time, check the aliases in annotate and alias for percentage signs — they will still have to be removed by 2028.
A separate item is the cache. Updating does not reset old records, so after rolling out, clear the page cache if you use cache_page or UpdateCacheMiddleware. And review the viewing rights in the admin area: leaks through changelist relate specifically to employees with read-only access.
The draft text was prepared with the participation of AI, the facts were checked against the original source — the official announcement of security releases on the Django project blog
2 декабря команда Django выпустила корректирующие релизы 6.1.4, 6.0.11 и 5.2.20. Они закрывают семь уязвимостей: две с высоким уровнем опасности, одну средней и четыре низкой. Исправления попали во все поддерживаемые ветки: 6.1, 6.0, 5.2 и main. Ветка 6.1 вдобавок получила семь обычных багфиксов, в том числе по регрессиям прошлого релиза.
Две уязвимости высокой опасности
Первая касается GeoDjango и PostGIS. Поле RasterField позволяло через пользовательское имя и нестандартный драйвер GDAL записать файл в произвольное место на сервере, а это потенциально открывает дорогу к выполнению кода. До поля можно было добраться штатно: через запасной CharField в формах, то есть через админку, ModelForm и сериализаторы с записью. Теперь RasterField по умолчанию не редактируется (editable равен False). Словарь или JSON-строка с нестандартным драйвером вызывают GDALException, а другой драйвер нужно явно обернуть в GDALRaster, отметив описание как доверенное. Разработчики предупреждают, что при недоверенном вводе остаётся риск SSRF. Поля геометрии дефект не затрагивает.
Вторая уязвимость — возможная SQL-инъекция в ORM-lookups range и in. Её открывали знаки процента в алиасах и в key transforms. Для range требовалось больше двух значений в правой части, для in — двусторонний transform. Теперь range принимает ровно два значения. Проценты в алиасах и key transforms объявлены устаревшими ещё в 6.0, их поддержку уберут в 2028 году.
Средняя и низкие
- XSS в фильтре truncatechars_html и в методе Truncator.chars с флагом html: срабатывал, когда длина текста совпадала с длиной обрезки, а результат выводился в HTML-атрибут.
- Отравление кеша: build_absolute_uri ошибочно нормализовал сегменты пути с точкой и двумя точками. При некоторых схемах развёртывания анонимный пользователь мог добиться, чтобы UpdateCacheMiddleware и cache_page отдавали закешированный ответ не по тому адресу. Теперь такие сегменты сохраняются.
- Две утечки данных в списке объектов админки: сотрудник с правом только на просмотр мог перебирать значения через алиас pk у модели с собственным первичным ключом OneToOneField (по умолчанию это модели с многотабличным наследованием) и через повторные lookups по обратным связям. Вторая проблема — регрессия, появившаяся в 5.0.3.
- Переполнение буфера в куче в OGRGeometry.wkb: на 64-битных платформах для геометрий больше 4 ГБ выделялся слишком маленький буфер. Затронуты также hex, geos и pickle.
Что ещё исправлено в 6.1.4
Ветка 6.1 получила исправления регрессий: падение executemany на Oracle, когда только часть строковых параметров длиннее 4000 символов; падение union, intersection и difference при сортировке модели по связанным полям; неверный результат отрицания nullable-BooleanField через ~F на SQLite. Добавлена совместимость с pylibmc 1.8.0, а режим FETCH_PEERS больше не возвращает None вместо ObjectDoesNotExist для удалённого связанного объекта.
Что это значит на практике
Обновляться стоит сразу, особенно проектам на GeoDjango и PostGIS. Если RasterField где-то редактируется через формы или API, после обновления поле пропадёт из ModelForm, и это может сломать сценарии загрузки растров. Проверьте их тестами и, если нужно, явно разрешите поле, но с проверкой драйвера.
Поиском по коду найдите вызовы range с переменным списком значений: если туда когда-то попадало больше двух элементов, теперь это ошибка. Заодно проверьте алиасы в annotate и alias на знаки процента — до 2028 года их всё равно придётся убрать.
Отдельный пункт — кеш. Старые записи обновление не сбрасывает, поэтому после выката очистите кеш страниц, если используете cache_page или UpdateCacheMiddleware. И пересмотрите права на просмотр в админке: утечки через changelist касаются именно сотрудников с доступом только на чтение.
Черновик текста подготовлен с участием ИИ, факты сверены с первоисточником — официальный анонс security-релизов в блоге проекта Django
Comments 5
Newest Popular