Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions extract.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"os"
"path/filepath"
"strings"
"time"
)

func (r *F2FSReader) cmdExtract(srcPath, dest string) error {
Expand All @@ -29,6 +30,39 @@ func (r *F2FSReader) cmdExtract(srcPath, dest string) error {
return r.extractFile(nid, srcPath, dest)
}

// applyMetadata restores the modification time this inode recorded on the
// real device, and a safe derivative of its permission bits, onto the
// freshly-written file or directory at outPath. Best-effort and
// silent-on-failure: this runs after the content is already written, so a
// metadata problem (e.g. an unrepresentable mode bit) must never turn into a
// lost file.
func applyMetadata(outPath string, in *Inode) {
os.Chmod(outPath, safeExtractedMode(in.IMode))
mtime := time.Unix(int64(in.IMtime), 0)
os.Chtimes(outPath, mtime, mtime)
}

// safeExtractedMode derives a permission mode for extracted output from the
// original inode's mode, not a verbatim copy of it. setuid/setgid/sticky
// bits are dropped: replaying a setuid-root bit from firmware onto a file in
// a shared analysis tree is a real local-privesc surface, not just a
// metadata detail. Read (and, for a directory, search) for everyone is
// always guaranteed on top of whatever the original bits were, so a later
// pipeline stage reading the extracted tree under a different uid than
// whoever ran the extractor can still open every file, the same guarantee
// this project's other extractors already give: ext4-backed firmware goes
// through debugfs's dump/rdump, which writes extracted output at the
// invoking process's default (typically world-readable) umask rather than
// replaying the original device's mode bits at all.
func safeExtractedMode(iMode uint16) os.FileMode {
perm := os.FileMode(iMode & 0o777)
perm |= 0o644
if isDir(iMode) {
perm |= 0o755
}
return perm
}

// Clean F2FS binary padding to prevent Linux syscall crashes
func parseSymlinkTarget(data []byte) string {
if idx := bytes.IndexByte(data, 0); idx >= 0 {
Expand Down Expand Up @@ -85,13 +119,18 @@ func (r *F2FSReader) extractFile(nid uint32, srcPath, dest string) error {
return err
}

in, err := r.getInode(nid)
if err != nil {
return err
}
data, err := r.readFile(nid, -1)
if err != nil {
return err
}
if err := os.WriteFile(outPath, data, 0644); err != nil {
return err
}
applyMetadata(outPath, in)
fmt.Printf("Extracted file: %s -> %s (%d bytes)\n", srcPath, outPath, len(data))
return nil
}
Expand All @@ -117,6 +156,9 @@ func (r *F2FSReader) extractDir(nid uint32, srcPath, dest string) error {

switch e.FileType {
case FTDir:
// extractDir applies its own directory's metadata itself, once
// every child underneath it (which would otherwise bump its
// mtime back to "now") is already written.
if err := r.extractDir(e.Ino, childSrc, childDst); err != nil {
fmt.Fprintf(os.Stderr, "Warning: extractdir %s: %v\n", childSrc, err)
}
Expand Down Expand Up @@ -145,6 +187,11 @@ func (r *F2FSReader) extractDir(nid uint32, srcPath, dest string) error {
fmt.Printf("Symlink: %s -> %s\n", childDst, targetStr)
}
default:
childIn, err := r.getInode(e.Ino)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: read inode %s: %v\n", childSrc, err)
continue
}
data, err := r.readFile(e.Ino, -1)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: read %s: %v\n", childSrc, err)
Expand All @@ -153,9 +200,14 @@ func (r *F2FSReader) extractDir(nid uint32, srcPath, dest string) error {
if err := os.WriteFile(childDst, data, 0644); err != nil {
fmt.Fprintf(os.Stderr, "Warning: write %s: %v\n", childDst, err)
} else {
applyMetadata(childDst, childIn)
fmt.Printf("Extracted: %s (%d bytes)\n", childDst, len(data))
}
}
}

if in, err := r.getInode(nid); err == nil {
applyMetadata(dest, in)
}
return nil
}
28 changes: 27 additions & 1 deletion f2fs.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ type F2FSReader struct {
sb Superblock
natBitmap []byte
blockSize, blocksPerSeg, natEntriesPerBlock int
// nid -> block address overrides from the checkpoint's NAT journal,
// more recent than (and authoritative over) the raw NAT table below.
// nil when unavailable (non-compact summary format); see journal.go.
natJournal map[uint32]uint32
}

func NewF2FSReader(imagePath string) (*F2FSReader, error) {
Expand All @@ -102,6 +106,7 @@ func NewF2FSReader(imagePath string) (*F2FSReader, error) {
f.Close()
return nil, err
}
r.natJournal = r.loadNATJournal()
return r, nil
}

Expand Down Expand Up @@ -226,6 +231,18 @@ func (r *F2FSReader) getNATEntry(nid uint32) (ino, blkAddr uint32, err error) {
}

func (r *F2FSReader) readNode(nid uint32) ([]byte, error) {
// The checkpoint's NAT journal, when present, overrides the raw table:
// it holds whatever changed most recently and has not been flushed back
// to the table yet, which is exactly the case the raw-table-only lookup
// below gets wrong.
if journalAddr, ok := r.natJournal[nid]; ok {
if data, err := r.readBlock(journalAddr); err == nil && le32(data, 4072) == nid {
return data, nil
}
// Journal entry present but its target didn't check out either;
// fall through to the raw-table path rather than giving up here.
}

_, blkAddr, err := r.getNATEntry(nid)
if err != nil {
return nil, fmt.Errorf("NAT lookup nid=%d: %w", nid, err)
Expand Down Expand Up @@ -256,7 +273,16 @@ func (r *F2FSReader) readNode(nid uint32) ([]byte, error) {
}
}
}
return data, nil
// Every candidate NAT copy (primary, and both raw set0/set1 alternates)
// pointed at a block whose footer does not actually belong to this nid.
// The on-disk raw NAT table can be stale relative to the checkpoint's NAT
// journal (entries not yet flushed back to their table slot), which this
// reader does not parse, so the true block address is unavailable here.
// Returning the wrong block's bytes as if they were nid's data silently
// produced a corrupt (typically zero-length) file with no diagnostic; an
// explicit error lets every caller here already fall back to a clean skip
// with a warning instead (see extractDir, listDir).
return nil, fmt.Errorf("nid=%d: no NAT copy resolved to a block whose footer matches (checkpoint NAT journal not parsed by this reader)", nid)
}

func (r *F2FSReader) parseInode(data []byte) *Inode {
Expand Down
149 changes: 149 additions & 0 deletions journal.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
//
// SPDX-FileCopyrightText: Sushrut1101
//
// SPDX-License-Identifier: GPL-3.0-only
//

package main


// F2FS batches recent NAT (node address table) updates into a journal
// embedded in the checkpoint, and only periodically flushes them back into
// the main on-disk NAT table blocks the rest of this reader walks. Right
// after a burst of writes the true location of a just-created inode can live
// only in this journal; the raw table still has a stale or empty entry for
// it. Confirmed against the real kernel implementation
// (fs/f2fs/segment.c:read_compacted_summaries, fs/f2fs/checkpoint.c:
// f2fs_get_valid_checkpoint) and f2fs-tools' f2fs_fs.h struct layout, not
// guessed: without this, resolving those nids from the raw table alone
// returns the wrong block, which readNode now reports as an error rather
// than returning as if it were correct.
const (
// struct f2fs_checkpoint field byte offsets (f2fs_fs.h). Fixed part is
// 192 bytes; MAX_ACTIVE_NODE_LOGS=8 and MAX_ACTIVE_DATA_LOGS=8 fields
// sit between free_segment_count and ckpt_flags.
cpVerOffset = 0 // __le64 checkpoint_ver
cpFlagsOffset = 132 // __le32 ckpt_flags
cpPackTotalBlksOffset = 136 // __le32 cp_pack_total_block_count
cpPackStartSumOffset = 140 // __le32 cp_pack_start_sum
cpCompactSumFlag = 0x00000004

// struct f2fs_journal (f2fs_fs.h): __le16 n_nats, followed by a union
// spare area also used for the SIT journal / extra info. In compact
// summary mode the whole 507-byte journal sits at byte 0 of the block
// at start_sum_block, ahead of any per-log summary entries (confirmed
// in read_compacted_summaries: "Step 1: restore nat cache" copies from
// kaddr, offset 0, before the summary-entries step that follows it).
natJournalNNatsOffset = 0
natJournalEntriesStart = 2
natJournalEntrySize = 13 // __le32 nid + f2fs_nat_entry{u8 version; le32 ino; le32 block_addr}
// NAT_JOURNAL_ENTRIES = (SUM_JOURNAL_SIZE(507) - 2) / 13
natJournalMaxEntries = 38
)

// verAfter mirrors the kernel's ver_after() macro: a is more recent than b,
// wraparound-safe via signed subtraction.
func verAfter(a, b uint64) bool {
return int64(a-b) > 0
}

// checkpointPack is one of the two redundant, self-mirrored checkpoint
// copies F2FS keeps for crash consistency.
type checkpointPack struct {
startAddr uint32
version uint64
flags uint32
packStartSum uint32
valid bool
}

// readCheckpointPack reads and internally validates one checkpoint pack: its
// header block must agree with its own footer copy (the last block of the
// pack, a repeated header) on the version number, the same consistency check
// f2fs_get_valid_checkpoint performs before trusting a pack.
func (r *F2FSReader) readCheckpointPack(startAddr uint32) checkpointPack {
header, err := r.readBlock(startAddr)
if err != nil {
return checkpointPack{}
}
version := le64(header, cpVerOffset)
totalBlocks := le32(header, cpPackTotalBlksOffset)
// Sanity bound: a pack can't be larger than one segment nor smaller
// than the two mirrored header/footer blocks it must contain.
if totalBlocks <= 2 || totalBlocks > uint32(r.blocksPerSeg) {
return checkpointPack{}
}
footerAddr := startAddr + totalBlocks - 1
footer, err := r.readBlock(footerAddr)
if err != nil {
return checkpointPack{}
}
if le64(footer, cpVerOffset) != version {
return checkpointPack{}
}
return checkpointPack{
startAddr: startAddr,
version: version,
flags: le32(header, cpFlagsOffset),
packStartSum: le32(header, cpPackStartSumOffset),
valid: true,
}
}

// loadNATJournal locates the current checkpoint pack and, when it uses the
// compact summary format, parses the NAT journal entries out of it. Returns
// nil (not an error) when no journal is available or it uses the
// non-compact per-log summary format this reader does not parse; readNode's
// existing raw-table path remains the fallback for those nids either way.
func (r *F2FSReader) loadNATJournal() map[uint32]uint32 {
pack1 := r.readCheckpointPack(r.sb.CPBlkAddr)
pack2 := r.readCheckpointPack(r.sb.CPBlkAddr + uint32(r.blocksPerSeg))

var current checkpointPack
switch {
case pack1.valid && pack2.valid:
if verAfter(pack2.version, pack1.version) {
current = pack2
} else {
current = pack1
}
case pack1.valid:
current = pack1
case pack2.valid:
current = pack2
default:
return nil
}

if current.flags&cpCompactSumFlag == 0 {
// Non-compact (per-log) summary format: the NAT journal is split
// across up to 3 separate node-log summary blocks instead of one
// merged block, a different layout this reader does not parse.
return nil
}

sumBlkAddr := current.startAddr + current.packStartSum
block, err := r.readBlock(sumBlkAddr)
if err != nil {
return nil
}

nNats := int(le16(block, natJournalNNatsOffset))
if nNats > natJournalMaxEntries {
nNats = natJournalMaxEntries
}
journal := make(map[uint32]uint32, nNats)
for i := 0; i < nNats; i++ {
off := natJournalEntriesStart + i*natJournalEntrySize
nid := le32(block, off)
// entry layout: nid(4) + ne{version(1) + ino(4) + block_addr(4)}.
// block_addr sits at off+9 (4 for nid, 1 for version, 4 for ino),
// not off+5 -- that offset is only right for the RAW nat table's
// f2fs_nat_entry, which has no leading nid field of its own.
blkAddr := le32(block, off+9)
if blkAddr != 0 && blkAddr != NewAddr && blkAddr < uint32(r.sb.BlockCount) {
journal[nid] = blkAddr
}
}
return journal
}