scripts/shell/breakfs.sh
2024-03-20 11:28:46 -05:00

57 lines
1.3 KiB
Bash
Executable file

#!/usr/bin/env bash
#
# Script to corrupt a linux ext3/4 partition
#
# SPDX-License-Identifier: MIT
# Check usage
if [ "$#" != "1" ]
then
echo "Usage: $0 /dev/sdb1"
exit 1
fi
# Check if the invoking user is root
if [ "$EUID" != "0" ]
then
echo 'Please run this script as a root privileged user'
exit 2
fi
# Find mount and check it's actually mounted
MOUNT=$(mount | grep "$1" | awk '{print $3}')
if [ -z "$MOUNT" ]
then
echo "$1 is not mounted, please mount it first"
exit 3
fi
# Find journal inode and block size from device
DUMP=$(dumpe2fs "$1" 2>&1 | grep -E -i "^Journal\ inode|^Block\ size")
INODE=$(echo "$DUMP" | grep inode | awk '{print $3}')
SIZE=$(echo "$DUMP" | grep size | awk '{print $3}')
# If foo exists delete it, then create it
if [ -e "$MOUNT/foo" ]
then
rm -f "$MOUNT/foo"
fi
touch "$MOUNT/foo"
sync
# Find block location of the journal
echo "stat <${INODE}>" > debugfs.cmd
BLOCK=$(debugfs -f debugfs.cmd "$1" 2>&1 | sed -nr 's/\([0-9-]+\):\ ?([0-9]+)-[0-9].+/\1/p')
rm -f debugfs.cmd
# Overwrite the first block of the journal
# shellcheck disable=SC2086
dd if=/dev/urandom of="$1" bs=$SIZE count=1 skip=$BLOCK > /dev/null 2>&1
sync
# Attempt to write to foo, and then remove it, at least one should fail
rm -f "$MOUNT/foo"
echo foo > "$MOUNT/bar"
# Exit
exit 0