fix(release): validate SQLite archive member format
This commit is contained in:
@@ -5,6 +5,7 @@ import gzip
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import shutil
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
@@ -310,11 +311,19 @@ class BackupPermissionTests(unittest.TestCase):
|
||||
with tempfile.TemporaryDirectory(prefix='backup-permission-') as directory:
|
||||
target = Path(directory) / 'synthetic-backup.gz'
|
||||
payload = b'synthetic permission fixture'
|
||||
if kind == 'recovery':
|
||||
output = io.BytesIO()
|
||||
with tarfile.open(fileobj=output, mode='w:gz') as bundle:
|
||||
member = tarfile.TarInfo('jobtracker.db')
|
||||
member.size = 16
|
||||
bundle.addfile(member, io.BytesIO(b'SQLite format 3\x00'))
|
||||
payload = output.getvalue()
|
||||
target.write_bytes(payload)
|
||||
script = '\n'.join([
|
||||
'set -euo pipefail',
|
||||
'BACKUP_DIR=' + shlex.quote(Path(directory).as_posix()),
|
||||
'TARGET=' + shlex.quote(target.as_posix()),
|
||||
'python3() { ' + shlex.quote(Path(sys.executable).as_posix()) + ' "$@"; }',
|
||||
'chmod() { echo "HOST PERMISSIONS"; return ' + str(host_status) + '; }',
|
||||
'docker() { if [[ "${@: -1}" == *chmod* ]]; then echo "FALLBACK PERMISSIONS"; return ' + str(fallback_status) + '; fi; return 0; }',
|
||||
'du() { printf "1K\\tsynthetic\\n"; }',
|
||||
@@ -414,7 +423,7 @@ class BackupSqlTrailerTests(unittest.TestCase):
|
||||
|
||||
|
||||
class BackupDatabaseMemberTests(unittest.TestCase):
|
||||
def verify_archive(self, member_name, truncated_tar=False):
|
||||
def verify_archive(self, member_name, truncated_tar=False, member_type=tarfile.REGTYPE, contents=None):
|
||||
source = (ROOT / 'deploy/deploy.sh').read_text(encoding='utf-8')
|
||||
functions = []
|
||||
for name in ['verify_backup_file_shape', 'verify_volume_backup']:
|
||||
@@ -424,23 +433,30 @@ class BackupDatabaseMemberTests(unittest.TestCase):
|
||||
folder = Path(temporary)
|
||||
archive = folder / 'synthetic.tar.gz'
|
||||
member = tarfile.TarInfo(member_name)
|
||||
member.type = member_type
|
||||
if member_type in (tarfile.SYMTYPE, tarfile.LNKTYPE):
|
||||
member.linkname = 'missing-database'
|
||||
if contents is None:
|
||||
database = folder / 'fixture.db'
|
||||
with sqlite3.connect(database) as connection:
|
||||
connection.execute('CREATE TABLE synthetic (id INTEGER PRIMARY KEY, value TEXT)')
|
||||
connection.execute("INSERT INTO synthetic(value) VALUES ('fixture only')")
|
||||
connection.close()
|
||||
contents = database.read_bytes()
|
||||
if truncated_tar:
|
||||
member.size = 4096
|
||||
with gzip.open(archive, 'wb') as bundle:
|
||||
bundle.write(member.tobuf())
|
||||
else:
|
||||
member.size = len(b'synthetic bytes')
|
||||
member.size = len(contents) if member_type == tarfile.REGTYPE else 0
|
||||
with tarfile.open(archive, 'w:gz') as bundle:
|
||||
bundle.addfile(member, io.BytesIO(b'synthetic bytes'))
|
||||
bundle.addfile(member, io.BytesIO(contents) if member_type == tarfile.REGTYPE else None)
|
||||
script = '\n'.join([
|
||||
'set -euo pipefail',
|
||||
'BACKUP_DIR=' + shlex.quote(folder.as_posix()),
|
||||
'python3() { ' + shlex.quote(Path(sys.executable).as_posix()) + ' "$@"; }',
|
||||
'report_backup() { echo "FORMAT VERIFIED"; }',
|
||||
# Replace container-only paths; run its actual tar and grep commands.
|
||||
r'docker() { local argument script="${!#}"; '
|
||||
r'for argument in "$@"; do case "$argument" in ARCHIVE_NAME=*) export "$argument";; esac; done; '
|
||||
r'script="${script//\/backup\//./}"; script="${script//\/tmp\/backup-members/backup-members}"; '
|
||||
r'(cd "$BACKUP_DIR" && sh -c "$script"); }',
|
||||
'docker() { echo "Unexpected Docker validation call" >&2; return 99; }',
|
||||
*functions,
|
||||
'if ! verify_volume_backup "$BACKUP_DIR/synthetic.tar.gz"; then exit 1; fi',
|
||||
'echo "NEXT DEPLOY GATE WOULD START"',
|
||||
@@ -472,6 +488,30 @@ class BackupDatabaseMemberTests(unittest.TestCase):
|
||||
self.assertNotIn('FORMAT VERIFIED', result.stdout)
|
||||
self.assertNotIn('NEXT DEPLOY GATE WOULD START', result.stdout)
|
||||
|
||||
def test_links_and_special_members_do_not_substitute_for_database_bytes(self):
|
||||
for kind in [tarfile.SYMTYPE, tarfile.LNKTYPE, tarfile.FIFOTYPE, tarfile.CHRTYPE]:
|
||||
with self.subTest(kind=kind):
|
||||
result = self.verify_archive('jobtracker.db', member_type=kind)
|
||||
self.assertNotEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
self.assertNotIn('FORMAT VERIFIED', result.stdout)
|
||||
self.assertNotIn('NEXT DEPLOY GATE WOULD START', result.stdout)
|
||||
|
||||
def test_empty_or_non_sqlite_database_bytes_block_the_next_gate(self):
|
||||
for contents in [b'', b'unrelated application bytes', b'SQLite format 3X\x00']:
|
||||
with self.subTest(contents=contents):
|
||||
result = self.verify_archive('jobtracker.db', contents=contents)
|
||||
self.assertNotEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
self.assertNotIn('FORMAT VERIFIED', result.stdout)
|
||||
self.assertNotIn('NEXT DEPLOY GATE WOULD START', result.stdout)
|
||||
|
||||
def test_unsafe_database_member_paths_block_the_next_gate(self):
|
||||
for name in ['../jobtracker.db', '/jobtracker.db', 'data/../../jobtracker.db']:
|
||||
with self.subTest(name=name):
|
||||
result = self.verify_archive(name)
|
||||
self.assertNotEqual(0, result.returncode, result.stdout + result.stderr)
|
||||
self.assertNotIn('FORMAT VERIFIED', result.stdout)
|
||||
self.assertNotIn('NEXT DEPLOY GATE WOULD START', result.stdout)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Check database member identity/type/header without extracting an archive.
|
||||
|
||||
This is format qualification, not SQLite integrity, a restore or recovery-set proof.
|
||||
"""
|
||||
from pathlib import PurePosixPath
|
||||
import sys
|
||||
import tarfile
|
||||
|
||||
|
||||
def validate(archive):
|
||||
found = False
|
||||
with tarfile.open(archive, mode='r|gz') as bundle:
|
||||
for member in bundle:
|
||||
path = PurePosixPath(member.name)
|
||||
if path.name != 'jobtracker.db':
|
||||
continue
|
||||
if path.is_absolute() or '..' in path.parts or '\\' in member.name:
|
||||
raise ValueError('SQLite backup has an unsafe database member path.')
|
||||
if not member.isfile() or member.size < 16:
|
||||
raise ValueError('SQLite backup database must be a nonempty regular file.')
|
||||
with bundle.extractfile(member) as data:
|
||||
if data.read(16) != b'SQLite format 3\x00':
|
||||
raise ValueError('SQLite backup database header is invalid.')
|
||||
found = True
|
||||
if not found:
|
||||
raise ValueError('SQLite backup contains no database member.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
if len(sys.argv) != 2:
|
||||
raise ValueError('Provide one SQLite backup archive.')
|
||||
validate(sys.argv[1])
|
||||
except (ValueError, OSError, EOFError, tarfile.TarError):
|
||||
# Archive names, member names and database contents may contain private data.
|
||||
print('SQLite backup member validation failed.', file=sys.stderr)
|
||||
sys.exit(1)
|
||||
Reference in New Issue
Block a user