File Restored, Label Gone: Checking xattr in GNU tar Archives
Reproducible GNU tar 1.35 A/B test: file bytes match, but a standard archive loses user xattr. We show a safe testbed, --xattrs parameters, and acceptance criteria.

In this article
Обычный архив GNU tar может вернуть байты файла и при этом не вернуть его расширенные атрибуты. Если они нужны приложению или политике хранения, создавайте и распаковывайте архив с явным --xattrs, ограничивайте нужное пространство имён и проверяйте метку после тестового восстановления. Совпавший SHA-256 подтверждает содержимое файла, но не xattr.
Почему совпавший SHA-256 не закрывает вопрос
Расширенный атрибут, или xattr, — это пара «имя — значение», связанная с объектом файловой системы отдельно от его содержимого. В Linux атрибуты разделены на пространства имён; для безопасного учебного теста используется только user.*. Такая структура расширенных атрибутов описана в справочной странице xattr(7).
Контрольная сумма вычисляется по байтам файла. Поэтому две восстановленные копии могут иметь один SHA-256, хотя одна сохранила user.backup_state, а другая — нет. Это разные свойства резервной копии, и проверять их нужно отдельно.
Что именно проверено
Тест выполнен 4 декабря 2026 года в изолированном каталоге с контролируемым шаблоном пути на Linux 6.18.64 с GNU tar 1.35, Bash 5.2.37 и Python 3.12.16. Исправленный сценарий запускался дважды и оба раза завершился кодом 0. Он не обращается к сети, службам или рабочим данным.
- Создаётся короткий учебный файл report.txt.
- Через Python ему назначается user.backup_state=checked, затем значение сразу читается обратно.
- Один архив создаётся обычным tar, второй — с --xattrs и фильтром user.*.
- Оба архива распаковываются в разные новые каталоги; затем отдельно проверяются xattr и SHA-256.
Безопасный A/B-тест
Скрипт записывает и удаляет данные только внутри каталога, который вернул mktemp. Переменные определены до использования, а trap удаляет стенд при обычном завершении и при ошибке. Запускайте его как отдельный файл в тестовой среде с файловой системой, которая поддерживает user xattr.
#!/usr/bin/env bash
set -euo pipefail
lab_root="${TMPDIR:-/tmp}"
lab_dir="$(mktemp -d "$lab_root/xattr-tar.XXXXXX")"
cleanup() {
case "$lab_dir" in
"$lab_root"/xattr-tar.*) rm -rf -- "$lab_dir" ;;
*) printf 'cleanup stopped: %s\n' "$lab_dir" >&2; return 1 ;;
esac
}
trap cleanup EXIT
source_dir="$lab_dir/source"
plain_restore="$lab_dir/plain-restore"
xattr_restore="$lab_dir/xattr-restore"
plain_archive="$lab_dir/plain.tar"
xattr_archive="$lab_dir/xattr.tar"
mkdir -p -- "$source_dir" "$plain_restore" "$xattr_restore"
printf '%s\n' 'backup payload' > "$source_dir/report.txt"
python3 - "$source_dir/report.txt" <<'PY'
import errno
import os
import sys
path = sys.argv[1]
os.setxattr(path, b"user.backup_state", b"checked")
print(os.getxattr(path, b"user.backup_state").decode())
PY
tar --create --file="$plain_archive" --directory="$source_dir" .
tar --create --xattrs --xattrs-include='user.*' --file="$xattr_archive" --directory="$source_dir" .
tar --extract --file="$plain_archive" --directory="$plain_restore"
tar --extract --xattrs --xattrs-include='user.*' --file="$xattr_archive" --directory="$xattr_restore"
python3 - "$plain_restore/report.txt" "$xattr_restore/report.txt" <<'PY'
import errno
import os
import sys
plain_path, xattr_path = sys.argv[1:]
try:
os.getxattr(plain_path, b"user.backup_state")
except OSError as error:
if error.errno != errno.ENODATA:
raise
print(f"plain=user.backup_state missing errno={error.errno}")
else:
raise AssertionError("plain archive unexpectedly restored user.backup_state")
value = os.getxattr(xattr_path, b"user.backup_state")
print(f"xattrs=user.backup_state {value.decode()}")
assert value == b"checked"
PY
sha256sum "$source_dir/report.txt" "$plain_restore/report.txt" "$xattr_restore/report.txt"
Сохраните текст как xattr-tar-lab.sh, проверьте его перед запуском и выполните от непривилегированного пользователя:
bash xattr-tar-lab.sh
Наблюдаемый вывод двух прогонов совпал:
checked
plain=user.backup_state missing errno=61
xattrs=user.backup_state checked
77c8166c510ab9bad0a1b1f7a207ef84664aeb9b02daad9c8525030401cb4076 …/source/report.txt
77c8166c510ab9bad0a1b1f7a207ef84664aeb9b02daad9c8525030401cb4076 …/plain-restore/report.txt
77c8166c510ab9bad0a1b1f7a207ef84664aeb9b02daad9c8525030401cb4076 …/xattr-restore/report.txt
Восстановление | SHA-256 содержимого | user.backup_state | Вывод |
|---|---|---|---|
Обычный tar | Совпадает | Отсутствует, errno=61 | Байты вернулись, xattr — нет |
tar --xattrs | Совпадает | checked | Байты и проверяемый xattr вернулись |
Число errno=61 — наблюдение именно этого Linux-стенда: атрибут не найден. В автоматизации не стоит переносить числовой код на другую ОС без проверки; важнее различать ожидаемое отсутствие атрибута и ошибку чтения по другим причинам.

Что делают параметры GNU tar
Руководство GNU tar 1.35 указывает, что расширенные атрибуты не сохраняются по умолчанию. Параметр --xattrs включает их обработку, а --xattrs-include='user.*' ограничивает выбранное пространство имён. В тесте эти параметры заданы и при создании, и при распаковке архива.
Функции os.setxattr и os.getxattr используются как проверяемый способ записать и прочитать значение; их Linux-доступность документирует Python 3.12. В рабочем процессе можно применять другой проверенный инструмент, но он должен читать конкретное имя атрибута после восстановления.
Как перенести проверку на реальную резервную копию
- Составьте перечень действительно нужных xattr и выясните, какая служба или политика их использует. Не включайте все пространства имён «на всякий случай».
- Создайте копию небольшого представительного набора в той же версии GNU tar и с теми же параметрами, что у задания резервного копирования.
- Распакуйте архив в новый пустой тестовый каталог на файловой системе назначения, не поверх рабочих данных.
- Сравните SHA-256 ожидаемых файлов и прочитайте каждое требуемое имя xattr с ожидаемым значением.
- Сохраните версию tar, параметры создания и распаковки, вывод проверок и коды завершения. Любое отсутствующее или неожиданное значение останавливает приёмку копии.
Если архив переносится на другой сервер или в объектное хранилище, проверяйте не только сам архив, но и итоговую файловую систему после распаковки. Поддержка xattr, политика монтирования и права процесса на целевой стороне могут отличаться.
Границы результата
- Тест охватывает только один атрибут user.backup_state из пространства user.* и не подтверждает сохранение POSIX ACL, SELinux-меток, Linux capabilities или пространств security.* и trusted.*.
- Совпавший xattr не доказывает полноту набора файлов, согласованность дампа базы или работоспособность приложения.
- Совпавший SHA-256 не подтверждает подлинность архива, если контрольную сумму могли заменить вместе с ним.
- Результат относится к GNU tar 1.35 и Linux-стенду; другая реализация tar, файловая система или ОС требует отдельной проверки.
- Архив с нужными метаданными ещё нужно защищать от несанкционированного чтения и изменения.
Проверка xattr дополняет, но не заменяет сверку архива с исходным каталогом и контроль целостности SHA-256. Эти проверки отвечают на разные вопросы.
Критерий готовности: тестовое восстановление на целевой файловой системе завершилось без ошибки, ожидаемые файлы имеют сохранённые контрольные суммы, а каждое обязательное имя xattr прочитано с ожидаемым значением. Только после этого можно считать проверенную часть метаданных восстановимой.
A standard GNU tar archive can restore file bytes while failing to restore extended attributes. If an application or storage policy requires them, create and extract archives with explicit --xattrs, restrict the namespace to what is needed, and verify the label after test restoration. A matching SHA-256 confirms file content but not xattr.
Why a Matching SHA-256 Does Not Close the Question
An extended attribute, or xattr, is a 'name–value' pair associated with a file system object separately from its content. In Linux, attributes are divided into namespaces; for a safe educational test, only the user.* namespace is used. This extended attribute structure is described in the xattr(7) manual page.
A checksum is calculated from file bytes. Therefore, two restored copies may share the same SHA-256 even if one retains user.backup_state and the other does not. These are distinct backup properties and must be verified separately.
What Exactly Was Verified
The test was run on December 4, 2026, in an isolated directory with a controlled path template on Linux 6.18.64 with GNU tar 1.35, Bash 5.2.37, and Python 3.12.16. The fixed script ran twice and completed with exit code 0 both times. It does not access networks, services, or production data.
- A short training file report.txt is created.
- Python assigns user.backup_state=checked to it, then immediately reads the value back.
- One archive is created with standard tar, the second with --xattrs and a user.* filter.
- Both archives are unpacked into separate new directories; then xattr and SHA-256 are checked separately.
Safe A/B Test
The script writes and deletes data only within the directory returned by mktemp. Variables are defined before use, and trap removes the test environment on normal exit and on error. Run it as a standalone file in a test environment with a file system that supports user xattr.
#!/usr/bin/env bash
set -euo pipefail
lab_root="${TMPDIR:-/tmp}"
lab_dir="$(mktemp -d "$lab_root/xattr-tar.XXXXXX")"
cleanup() {
case "$lab_dir" in
"$lab_root"/xattr-tar.*) rm -rf -- "$lab_dir" ;;
*) printf 'cleanup stopped: %s\n' "$lab_dir" >&2; return 1 ;;
esac
}
trap cleanup EXIT
source_dir="$lab_dir/source"
plain_restore="$lab_dir/plain-restore"
xattr_restore="$lab_dir/xattr-restore"
plain_archive="$lab_dir/plain.tar"
xattr_archive="$lab_dir/xattr.tar"
mkdir -p -- "$source_dir" "$plain_restore" "$xattr_restore"
printf '%s\n' 'backup payload' > "$source_dir/report.txt"
python3 - "$source_dir/report.txt" <<'PY'
import errno
import os
import sys
path = sys.argv[1]
os.setxattr(path, b"user.backup_state", b"checked")
print(os.getxattr(path, b"user.backup_state").decode())
PY
tar --create --file="$plain_archive" --directory="$source_dir" .
tar --create --xattrs --xattrs-include='user.*' --file="$xattr_archive" --directory="$source_dir" .
tar --extract --file="$plain_archive" --directory="$plain_restore"
tar --extract --xattrs --xattrs-include='user.*' --file="$xattr_archive" --directory="$xattr_restore"
python3 - "$plain_restore/report.txt" "$xattr_restore/report.txt" <<'PY'
import errno
import os
import sys
plain_path, xattr_path = sys.argv[1:]
try:
os.getxattr(plain_path, b"user.backup_state")
except OSError as error:
if error.errno != errno.ENODATA:
raise
print(f"plain=user.backup_state missing errno={error.errno}")
else:
raise AssertionError("plain archive unexpectedly restored user.backup_state")
value = os.getxattr(xattr_path, b"user.backup_state")
print(f"xattrs=user.backup_state {value.decode()}")
assert value == b"checked"
PY
sha256sum "$source_dir/report.txt" "$plain_restore/report.txt" "$xattr_restore/report.txt"
Save the text as xattr-tar-lab.sh, verify it before running, and execute it as a non-privileged user:
bash xattr-tar-lab.sh
The observed output from two runs matched:
checked
plain=user.backup_state missing errno=61
xattrs=user.backup_state checked
77c8166c510ab9bad0a1b1f7a207ef84664aeb9b02daad9c8525030401cb4076 …/source/report.txt
77c8166c510ab9bad0a1b1f7a207ef84664aeb9b02daad9c8525030401cb4076 …/plain-restore/report.txt
77c8166c510ab9bad0a1b1f7a207ef84664aeb9b02daad9c8525030401cb4076 …/xattr-restore/report.txt
Recovery | SHA-256 of content | user.backup_state | Output |
|---|---|---|---|
Standard tar | Matches | Missing, errno=61 | Bytes returned, xattrs not |
tar --xattrs | Match | checked | Bytes and verified xattr returned |
The errno=61 observation is specific to this Linux test environment: the attribute was not found. In automation, do not transfer numeric codes to another OS without verification; it is more important to distinguish between the expected absence of an attribute and a read error caused by other reasons.

What GNU tar parameters do
GNU tar 1.35 manual states that extended attributes are not preserved by default. The --xattrs parameter enables their processing, while --xattrs-include='user.*' restricts the selected namespace. In the test, these parameters are specified both during archive creation and extraction.
The os.setxattr and os.getxattr functions are used as a verified method to write and read values; their Linux availability is documented in Python 3.12. In a workflow, another verified tool may be used, but it must read the specific attribute name after restoration.
How to Move the Check to a Real Backup
- Compile a list of the xattrs that are actually needed and determine which service or policy uses them. Do not include all namespaces "just in case".
- Create a copy of a small representative set using the same GNU tar version and the same parameters as the backup job.
- Extract the archive into a new empty test directory on the target file system, not over live data.
- Compare the SHA-256 hashes of the expected files and read each required xattr name against its expected value.
- Save the tar version, creation and extraction parameters, check output, and exit codes. Any missing or unexpected value halts acceptance of the copy.
If the archive is moved to another server or an object storage, check not only the archive itself but also the final file system after extraction. xattr support, mount policies, and process permissions on the target side may differ.
Result Boundaries
- The test covers only the user.backup_state attribute from the user.* namespace and does not confirm the preservation of POSIX ACLs, SELinux labels, Linux capabilities, or security.* and trusted.* namespaces.
- A matching xattr does not prove the completeness of the file set, the consistency of the database dump, or the application's operability.
- A matching SHA-256 hash does not confirm the archive's authenticity if the checksum could have been replaced along with it.
- The result applies to GNU tar 1.35 and the Linux test stand; a different tar implementation, file system, or OS requires separate verification.
- The archive with the required metadata still needs protection against unauthorized reading and modification.
The xattr check complements, but does not replace, comparing the archive with the original directory and SHA-256 integrity verification. These checks answer different questions.
Readiness criterion: the test restore on the target file system completed without error, the expected files have preserved checksums, and every mandatory xattr name was read with the expected value. Only then can the verified portion of metadata be considered recoverable.





Discussion 0
Share your experience and ask questions. Comments without links appear after editorial review.
No comments yet. Start the discussion.