diff --git a/README.md b/README.md index 08a7547..fa300c4 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ Usage: Flags: --absolute output absolute paths, which is what hashdeep does without -l --allow-moved allow an audit to pass when known files have moved or been renamed but are unmodified + --allow-new allow an audit to pass when there are files which are not in the audit file -a, --audit string audit against supplied file; accepts hashdeep, sum (md5sum, sha256sum etc...) or hashit sqlite format --debug enable debug output --exclude-dir strings directories to exclude when walking directories, by name such as node_modules or the end of a path such as vendor/cache @@ -299,6 +300,8 @@ $ rm -rf /tmp/hashit-audit-test audit.txt `hashit` can also detect moved files, distinguishing them from new or missing files. As with `hashdeep`, an audit only passes when every file is exactly where it was, so moved files cause the audit to fail. To check that every known file is still present and unmodified, while allowing files to have been moved or renamed, use `--allow-moved`. New, missing or modified files still fail the audit. Files are matched by path first, so a file renamed onto the path of another known file, such as two files swapping names, is reported as modified rather than moved. +Files which are not in the audit file are reported as new and fail the audit, as with `hashdeep`, such as another audit file created in the same directory. To only verify the files the audit file lists, as `md5sum -c` does, use `--allow-new`. New files are still listed with `-v`, and missing or modified files still fail the audit. A copy of a known file whose original is still present is a new file, so passes with `--allow-new`. The two flags can be combined. + ```shell $ mv a.txt archive/a.txt $ hashit --allow-moved -a audit.txt . @@ -331,6 +334,7 @@ Some other points worth knowing: - A file which cannot be read, including files in a directory which cannot be read, is reported as could not be read in `-v` output, counted as missing when it is in the audit file and not counted otherwise, and `hashit` exits with `2` rather than `1`. - The same file supplied more than once by the same absolute path, such as through `.` and `./sub`, is only counted once. The same file reached through a symbolic link is a different path, so is counted again. - Modification times are recorded with `--mtime` but are not compared by an audit. +- A `sum` file which lists the same file more than once, such as once with `md5sum` and again with `sha1sum`, or as both `./file` and `file`, has every line checked as `md5sum -c` does, including when its paths only name the same file through the directory containing the `sum` file or a symbolic link, where a line is only not reported on its own when another line was checked against that same file and it names that file through the directory the audit is matched through, and a file listed with different values of the same hash is reported as modified with a warning. In a `hashdeep` file only the first entry for a path is used, with a warning. In a SQLite database a row for a path already listed with the same values is not counted, with a warning, while one with other values is reported as missing. Entries are only the same path when they name the same file through the directory the audit is matched through, so after a tree is copied elsewhere an absolute entry into the original is audited on its own. When every file matched an absolute entry no directory is chosen, and entries are the same path when they name the same file through the invoked from directory, or for a `sum` file, which has none, through any of them. A SQLite database whose `file_hashes` table does not have a text `filepath` on every row as its primary key compared exactly, as one not created by hashit may not, is refused rather than audited. - The audit file of an empty directory passes when audited against an empty directory, as does an audit file which is empty or only contains comments, which `md5sum -c` treats as an error. `hashdeep` reports an error for an audit file with no files in it. - An audit file written by a shell redirect into the directory being hashed, such as `hashit --format hashdeep . > manifest.txt`, lists itself as an empty file. That entry is ignored when auditing, but `--output manifest.txt` avoids it entirely and is recommended, especially for the `sum` format which writes as it goes and so may record part of itself, which then fails when audited from another directory. - Concatenated `hashdeep` files are read, but only the first `## Invoked from:` line is used, so files concatenated from different directories may report moved files. `hashdeep` also fails to audit these. @@ -351,7 +355,7 @@ hashdeep: Audit passed #### Paths in Audit Files -Relative paths in a `hashdeep` file are resolved against the directory recorded in its `## Invoked from:` line, so an audit file created with `hashit --format hashdeep .` can be audited from anywhere using either a relative or absolute path. When the invoked from directory does not contain the files, such as after they have been copied elsewhere, paths are also resolved against the directory containing the audit file, being where the file really is and then where the path supplied for it is when that is a symbolic link, and then the current directory. Relative paths in `sum` files have no invoked from directory, so are resolved against the current directory first. Matching is case sensitive on every platform. Paths are always compared as absolute paths, so the path to audit may be supplied as relative or absolute, and `./file` and `file` are the same file. So a manifest stored at the root of a set of files, created from that directory, can be audited from anywhere after the files are copied or shipped elsewhere. Symbolic links in the path to audit are not resolved, so a manifest created through `real/` and audited through a link to it reports every file as moved, as `hashdeep` does. When two files on disk match the same record, such as when the path to audit overlaps a copy of the files, the one matching through the invoked from directory is used and the other is reported as new. +Relative paths in a `hashdeep` file are resolved against the directory recorded in its `## Invoked from:` line, so an audit file created with `hashit --format hashdeep .` can be audited from anywhere using either a relative or absolute path. When the invoked from directory does not contain the files, such as after they have been copied elsewhere, paths are also resolved against the directory containing the audit file, being where the file really is and then where the path supplied for it is when that is a symbolic link, and then the current directory. An audit is matched through only one of these, the one through which the most files match their records, or the first of those in this order, so a file found only through another, such as a file moved to where the directory containing the audit file places its record, is reported as moved or new. Relative paths in `sum` files have no invoked from directory, so are resolved against the current directory first. Matching is case sensitive on every platform. Paths are always compared as absolute paths, so the path to audit may be supplied as relative or absolute, and `./file` and `file` are the same file. So a manifest stored at the root of a set of files, created from that directory, can be audited from anywhere after the files are copied or shipped elsewhere. Symbolic links in the path to audit are not resolved, so a manifest created through `real/` and audited through a link to it reports every file as moved, as `hashdeep` does. When the current directory was reached through a symbolic link, paths through where it, or a directory containing it, really is are compared through the link, so a manifest of absolute paths through `real/` audited with `.` from the link passes. A path containing `..`, such as `../dir` or `link/../dir`, names the directory the operating system reads, being the parent of the directory a symbolic link points to rather than the directory containing the link, in the paths supplied, the paths recorded in audit files and with `--absolute`. Where removing the `..` names the same directory, such as from a current directory reached through a symbolic link, the path is kept as written, A recorded path through a directory which no longer exists, such as the directory an audit file was created in, has its `..` removed as text, as a missing directory cannot be a symbolic link, while a recorded path with `..` after a link which no longer exists, a file, or a directory which cannot be searched never matches another file. When two files on disk match the same record, such as when the path to audit overlaps a copy of the files, the one matching through the invoked from directory is used and the other is reported as new. If the audit file is inside the directory being audited it is skipped, as it can never contain its own hash. `hashdeep` and `md5sum` do not do this, so when generating a file for them to verify, write it outside the directory being hashed, otherwise they will report the partially written file as changed. @@ -364,7 +368,7 @@ $ md5sum * > checksums.md5 $ hashit -a checksums.md5 . ``` -Note that `md5sum *` does not include files in subdirectories, while `hashit` audits the whole directory, so for a directory with subdirectories generate the file with something like `find . -type f -exec md5sum {} +`. +Note that `md5sum *` does not include files in subdirectories, while `hashit` audits the whole directory, so for a directory with subdirectories generate the file with something like `find -L . -type f -exec md5sum {} +`, where `-L` follows symbolic links as `hashit` does. The hash is determined by the file extension where it is one of `.md4`, `.md5`, `.sha1`, `.sha224`, `.sha256`, `.sha384`, `.sha512`, `.sha3-224`, `.sha3-256`, `.sha3-384`, `.sha3-512`, `.b2` or `.blake2b` (Blake2b-512 or Blake2b-256), `.b3` or `.blake3`, `.ed2k`, or `.crc32`, and otherwise by the length of the hash. A hash of 8 characters is assumed to be `crc32` and one of 16 `xxhash64`. Where lengths are shared the more common hash is assumed, being `md5` over `md4` and `ed2k`, `sha224` over `sha3-224`, `sha256` over `sha3-256`, `blake3` and `b2sum -l 256`, `sha384` over `sha3-384`, and `sha512` over `sha3-512` and `b2sum`. A wrong guess reports every file as modified, so name `b2sum` files `.b2` or use `--tag` output for the others. Relative paths are resolved against both the current directory and the directory containing the sum file, so run the audit from the directory the sum file was created in, or keep the sum file at the root of the files it lists. @@ -437,7 +441,7 @@ If a file is modified, the audit will fail and report the change, and `-v` lists $ hashit --hash all -a audit.db . ``` -The database is opened read-only and is never modified by an audit. If another tool has switched the database to WAL mode, SQLite creates `-wal` and `-shm` files next to it, and the audit fails when the directory is read only, so run `sqlite3 audit.db 'pragma journal_mode=delete'` first. Which files have been seen is tracked in a temporary table, which SQLite moves to a file once it outgrows its cache, so memory use does not grow with the size of the database. The table is created in SQLite's temporary directory, which can be changed by setting `SQLITE_TMPDIR` for very large audits. Files on disk which are not in the database, being new or moved files, are held in memory until the end of the audit, so auditing a directory with many new files will use more memory. The directory `hashit` was run from is stored in the database, and paths are matched the same way as `hashdeep` files, see [Paths in Audit Files](#paths-in-audit-files), so a database of relative paths can be audited from any directory using relative or absolute paths, and a database stored at the root of a set of files can be audited after they are copied elsewhere. To do this the absolute path of every record is first indexed in a temporary table. +The database is opened read-only and is never modified by an audit. If another tool has switched the database to WAL mode, SQLite creates `-wal` and `-shm` files next to it, and the audit fails when the directory is read only, so run `sqlite3 audit.db 'pragma journal_mode=delete'` first. Which files have been seen is tracked in a temporary table, which SQLite moves to a file once it outgrows its cache, so memory use does not grow with the size of the database. The table is created in SQLite's temporary directory, which can be changed by setting `SQLITE_TMPDIR` for very large audits. Files on disk which are not in the database, being new or moved files, are held in memory until the end of the audit, so auditing a directory with many new files will use more memory. The directory `hashit` was run from is stored in the database, and paths are matched the same way as `hashdeep` files, see [Paths in Audit Files](#paths-in-audit-files), so a database of relative paths can be audited from any directory using relative or absolute paths, and a database stored at the root of a set of files can be audited after they are copied elsewhere. Records are looked up by the path of each file relative to these directories, and records written another way, such as with `..` or `//`, are first indexed by their absolute path in a temporary table. ```shell # Example of a failed audit after modifying a file diff --git a/main.go b/main.go index 31071f6..3fc8a67 100644 --- a/main.go +++ b/main.go @@ -104,6 +104,12 @@ func main() { false, "allow an audit to pass when known files have moved or been renamed but are unmodified", ) + flags.BoolVar( + &processor.AllowNew, + "allow-new", + false, + "allow an audit to pass when there are files which are not in the audit file", + ) flags.BoolVar( &processor.Absolute, "absolute", diff --git a/processor/audit.go b/processor/audit.go index 0952095..133a472 100644 --- a/processor/audit.go +++ b/processor/audit.go @@ -49,7 +49,7 @@ func isSQLiteDB(filePath string) bool { // mode, as an audit should never modify the thing it is auditing. A single connection is used // as the temporary tables used during the audit only exist for the connection that created them func connectSqliteDbReadOnly(pathName string) (*sql.DB, error) { - abs, err := filepath.Abs(pathName) + abs, err := osAbs(pathName) if err != nil { return nil, err } @@ -136,6 +136,34 @@ func sqliteAuditHashes(pathName string) ([]string, error) { return nil, errors.New("audit database was created by an older development version of hashit, regenerate it with --format sqlite --overwrite") } + // each path is looked up as a single row compared exactly as text and rows are told apart by + // rowid, so a table made some other way could have a path listed twice with only one audited, + // a path matching a file differing in case or spelling of a number, a rowid column, which may + // be generated, hiding the real one, or a row without a path + var keyed, shadowed, withoutRowid, text, collates, nullPath int + var collation sql.NullString + if err := db.QueryRow(`select + (select count(*) = 1 and sum(name = 'filepath') = 1 from pragma_table_info('file_hashes') where pk > 0), + (select count(*) from pragma_table_xinfo('file_hashes') where lower(name) in ('rowid', 'oid', '_rowid_')), + (select count(*) from pragma_table_list where name = 'file_hashes' and wr = 1), + (select count(*) from pragma_table_info('file_hashes') where name = 'filepath' and lower(type) = 'text'), + (select count(*) from sqlite_master where name = 'file_hashes' and lower(sql) like '%collate%'), + exists (select 1 from file_hashes where filepath is null)`).Scan(&keyed, &shadowed, &withoutRowid, &text, &collates, &nullPath); err != nil { + return nil, err + } + var index sql.NullString + if err := db.QueryRow("select name from pragma_index_list('file_hashes') where origin = 'pk'").Scan(&index); err != nil && !errors.Is(err, sql.ErrNoRows) { + return nil, err + } + if index.Valid { + if err := db.QueryRow("select coll from pragma_index_xinfo(?) where key = 1", index.String).Scan(&collation); err != nil && !errors.Is(err, sql.ErrNoRows) { + return nil, err + } + } + if keyed != 1 || shadowed != 0 || withoutRowid != 0 || text != 1 || collates != 0 || nullPath != 0 || !strings.EqualFold(collation.String, "binary") { + return nil, errors.New("audit database was not created by hashit, its file_hashes table must have a text filepath on every row as its primary key, compared exactly, and a rowid") + } + // a database of an empty directory has no records, and passes when audited against one // databases record which hashes they hold, but those from earlier development builds do not, // in which case the first row is used @@ -214,7 +242,8 @@ on conflict (abs) do update set filepath = excluded.filepath, level = excluded.l if err := rows.Scan(&rid, &filePath); err != nil { return err } - if isDirectSpelling(filePath) { + direct := isDirectSpelling(filePath) + if direct && len(workingDirAncestors()) == 0 { continue } var keys []string @@ -224,6 +253,11 @@ on conflict (abs) do update set filepath = excluded.filepath, level = excluded.l continue } keys = append(keys, k) + // when the working directory was reached through a symlink a path can be compared + // as another spelling, which sqliteLookup does not try, so only those are indexed + if direct && k == absPath(base, filePath) { + continue + } if _, err := insert.ExecContext(ctx, k, filePath, level, rid); err != nil { return err } @@ -237,7 +271,7 @@ on conflict (abs) do update set filepath = excluded.filepath, level = excluded.l } // isDirectSpelling reports whether sqliteLookup finds a record by its path without the index, -// being a clean absolute path, or a clean relative path optionally starting with ./ +// being a clean absolute path, or a clean relative path without .. optionally starting with ./ func isDirectSpelling(p string) bool { if filepath.IsAbs(p) { return filepath.Clean(p) == p @@ -246,8 +280,13 @@ func isDirectSpelling(p string) bool { if p == "" || filepath.VolumeName(p) != "" || os.IsPathSeparator(p[0]) { return false } + // sqliteLookup only tries the path relative to each directory, which never goes up and back + // down again such as ../sub/a, so any path with .. is left to the index p = strings.TrimPrefix(p, "."+string(filepath.Separator)) - return p != "" && filepath.Clean(p) == p + if p == "" || os.IsPathSeparator(p[0]) || p == ".." || strings.HasPrefix(p, ".."+string(filepath.Separator)) { + return false + } + return filepath.Clean(p) == p } // sqliteLookup finds the record for the absolute path of a file on disk, returning its path in @@ -263,13 +302,14 @@ func sqliteLookup(ctx context.Context, tx *sql.Tx, bases []string, abs string) ( if rel, err := filepath.Rel(base, abs); err == nil && rel != "." && absFrom(base, rel) == abs { candidates = append(candidates, rel, "."+string(filepath.Separator)+rel) } - for len(candidates) < 3 { + if len(candidates) == 0 { candidates = append(candidates, nil) } + in := strings.Repeat("?, ", len(candidates)-1) + "?" var filePath string err := tx.QueryRowContext(ctx, `select filepath from ( - select rowid as rid, filepath from file_hashes where filepath in (?, ?, ?) + select rowid as rid, filepath from file_hashes where filepath in (`+in+`) union all select rid, filepath from temp.paths where abs = ? and level = ? ) order by rid limit 1`, append(candidates, abs, level)...).Scan(&filePath) @@ -284,6 +324,167 @@ func sqliteLookup(ctx context.Context, tx *sql.Tx, bases []string, abs string) ( return "", 0, false, nil } +// claimSqliteMatches decides which file on disk claims each record once the directory the audit +// is matched through is chosen, see chooseLevel, recording it in temp.seen. Files matching through +// another directory and files losing a record to another are returned so they are treated as new. +// Two files on disk can resolve to the same record, so which claims it does not depend on the +// order files were processed in. A file matching through a directory earlier in priority order +// wins, being the record's own path before another directory, then the first path in sort order +func claimSqliteMatches(ctx context.Context, tx *sql.Tx, chosen int) (int, int, []Result, error) { + if _, err := tx.ExecContext(ctx, `create temp table seen ( + filepath text primary key, + status integer not null, + disk_file text not null unique +)`); err != nil { + return 0, 0, nil, err + } + if _, err := tx.ExecContext(ctx, `insert into temp.seen (filepath, status, disk_file) +select filepath, status, disk_file from ( + select filepath, status, disk_file, row_number() over (partition by filepath order by level, disk_file) as n + from temp.matches where independent = 1 or ? = -1 or level = ? +) where n = 1`, chosen, chosen); err != nil { + return 0, 0, nil, err + } + + matched, modified := 0, 0 + rows, err := tx.QueryContext(ctx, "select status, count(*) from temp.seen group by status") + if err != nil { + return 0, 0, nil, err + } + for rows.Next() { + var status, n int + if err := rows.Scan(&status, &n); err != nil { + _ = rows.Close() + return 0, 0, nil, err + } + if FileStatus(status) == FileMatched { + matched += n + } else { + modified += n + } + } + if err := rows.Err(); err != nil { + _ = rows.Close() + return 0, 0, nil, err + } + _ = rows.Close() + + rows, err = tx.QueryContext(ctx, "select disk_file, result from temp.matches where disk_file not in (select disk_file from temp.seen)") + if err != nil { + return 0, 0, nil, err + } + defer rows.Close() + var unclaimed []Result + for rows.Next() { + var diskFile, result string + if err := rows.Scan(&diskFile, &result); err != nil { + return 0, 0, nil, err + } + var res Result + if err := json.Unmarshal([]byte(result), &res); err != nil { + return 0, 0, nil, err + } + // JSON replaces bytes which are not UTF-8, so the name is taken from disk_file + res.File = diskFile + unclaimed = append(unclaimed, res) + } + return matched, modified, unclaimed, rows.Err() +} + +// markSqliteDuplicates records in temp.duplicates the rows no file on disk was checked against +// which name the same path through the directory the audit is matched through as another row with +// the same values, such as from hashing . and ./sub together, as otherwise the row is never looked +// up and is reported as missing although the file exists. Of such rows the earliest is kept when +// none was checked. A row with other values, or naming another path through that directory such as +// an absolute path into a tree which was copied elsewhere, is still reported. When no directory was +// chosen the directory hashit was invoked from is used, as the database records it +func markSqliteDuplicates(ctx context.Context, tx *sql.Tx, base string) (int, error) { + if _, err := tx.ExecContext(ctx, "create temp table duplicates (rid integer primary key)"); err != nil { + return 0, err + } + var unseen bool + if err := tx.QueryRowContext(ctx, "select exists (select 1 from file_hashes where filepath not in (select filepath from temp.seen))").Scan(&unseen); err != nil || !unseen { + return 0, err + } + // only rows whose name and values are listed more than once can be duplicates, so when many + // files are missing they are not all resolved. Values are compared as fileHashToRecord reads + // them, and the name is what follows the last separator. A row this misses is still reported + path := `replace(filepath, '\', '/')` + values := []string{"substr(" + path + ", length(rtrim(" + path + ", replace(" + path + ", '/', ''))) + 1)"} + for _, column := range []string{"crc32", "xxhash64", "md4", "md5", "sha1", "sha224", "sha256", "sha384", "sha512", + "blake2b_256", "blake2b_512", "blake3", "sha3_224", "sha3_256", "sha3_384", "sha3_512", "ed2k"} { + values = append(values, "lower(ifnull("+column+", ''))") + } + key := "size || '|' || " + strings.Join(values, " || '|' || ") + if _, err := tx.ExecContext(ctx, "create temp table repeated (rid integer primary key, key text not null)"); err != nil { + return 0, err + } + if _, err := tx.ExecContext(ctx, `insert into temp.repeated select f.rowid, `+key+` from file_hashes f +where `+key+` in (select `+key+` from file_hashes group by 1 having count(*) > 1)`); err != nil { + return 0, err + } + + // rows with the same values are read together, so only the paths of one set are held at a time + rows, err := tx.QueryContext(ctx, `select r.rid, r.key, f.filepath, f.filepath in (select filepath from temp.seen) +from temp.repeated r join file_hashes f on f.rowid = r.rid order by r.key, r.rid`) + if err != nil { + return 0, err + } + type samePath struct { + checked bool + unseen []int64 // in rowid order + } + var duplicates []int64 + paths := map[string]*samePath{} + settle := func() { + for _, p := range paths { + if !p.checked { + p.unseen = p.unseen[1:] + } + duplicates = append(duplicates, p.unseen...) + } + paths = map[string]*samePath{} + } + current := "" + for rows.Next() { + var rid int64 + var values, filePath string + var checked bool + if err := rows.Scan(&rid, &values, &filePath, &checked); err != nil { + _ = rows.Close() + return 0, err + } + if values != current { + settle() + current = values + } + k := absFrom(base, filePath) + p := paths[k] + if p == nil { + p = &samePath{} + paths[k] = p + } + if checked { + p.checked = true + } else { + p.unseen = append(p.unseen, rid) + } + } + if err := rows.Err(); err != nil { + _ = rows.Close() + return 0, err + } + _ = rows.Close() + settle() + + for _, rid := range duplicates { + if _, err := tx.ExecContext(ctx, "insert into temp.duplicates (rid) values (?)", rid); err != nil { + return 0, err + } + } + return len(duplicates), nil +} + // doSqliteAudit performs an audit against a SQLite database, comparing all available hashes. // To scale to databases larger than available memory, which files have been seen is tracked // in a temporary table rather than in memory, and the final report streams over the database @@ -310,14 +511,15 @@ func doSqliteAudit(input chan Result) (string, bool) { return "", false } - // result holds the file on disk for a record matched through a directory other than the one - // hashit was invoked from, as a file matching the record's own path may later take it over - _, err = db.Exec(`create temp table seen ( - filepath text primary key, + // every file matching a record is held until the directory the audit is matched through is + // chosen, see chooseLevel, with its result so it can be treated as new + _, err = db.Exec(`create temp table matches ( + disk_file text primary key, + filepath text not null, status integer not null, - disk_file text not null, - is_primary integer not null, - result text + level integer not null, + independent integer not null, + result text not null )`) if err != nil { printError(fmt.Sprintf("failed to create temporary audit table: %s", err.Error())) @@ -330,7 +532,7 @@ func doSqliteAudit(input chan Result) (string, bool) { printError(fmt.Sprintf("failed to begin audit transaction: %s", err.Error())) return "", false } - insertSeen, err := tx.PrepareContext(ctx, "insert or ignore into temp.seen (filepath, status, disk_file, is_primary, result) values (?, ?, ?, ?, ?)") + insertMatch, err := tx.PrepareContext(ctx, "insert or ignore into temp.matches (disk_file, filepath, status, level, independent, result) values (?, ?, ?, ?, ?, ?)") if err != nil { _ = tx.Rollback() printError(fmt.Sprintf("failed to prepare audit statement: %s", err.Error())) @@ -339,25 +541,26 @@ func doSqliteAudit(input chan Result) (string, bool) { txQueries := queries.WithTx(tx) examinedCount := 0 - matched := 0 - filesModified := 0 // new files are usually few, so are held in memory indexed by hash to identify moves var newFileCandidates []Result - // lookupRecord finds the record for a file on disk by its absolute path, and whether it matched - // through the directory hashit was invoked from - lookupRecord := func(file string) (*AuditRecord, bool, error) { - filePath, level, ok, err := sqliteLookup(ctx, tx, bases, absFrom(cwd, file)) + // lookupRecord finds the record for a file on disk by its absolute path, with the priority of + // the directory it matched through and whether its path names the file through every directory + lookupRecord := func(file string) (*AuditRecord, int, bool, error) { + abs := absFrom(cwd, file) + filePath, level, ok, err := sqliteLookup(ctx, tx, bases, abs) if err != nil || !ok { - return nil, false, err + return nil, 0, false, err } row, err := txQueries.FileHashByFilePath(ctx, filePath) if err != nil { - return nil, false, err + return nil, 0, false, err } - return fileHashToRecord(row), level == 0, nil + // an absolute path names the same file through every directory, see baseLevel + return fileHashToRecord(row), level, filepath.IsAbs(filePath), nil } + votes := map[int]int{} seenFiles := map[string]bool{} for res := range input { @@ -367,7 +570,7 @@ func doSqliteAudit(input chan Result) (string, bool) { } examinedCount++ - record, primary, err := lookupRecord(res.File) + record, level, independent, err := lookupRecord(res.File) if err != nil { printError(fmt.Sprintf("failed to query audit database for file %s: %s", res.File, err.Error())) continue @@ -381,75 +584,35 @@ func doSqliteAudit(input chan Result) (string, bool) { if recordMatches(record, res) { status = FileMatched } - - var stored sql.NullString - if !primary { - b, err := json.Marshal(res) - if err != nil { - printError(fmt.Sprintf("failed to record audit result for file %s: %s", res.File, err.Error())) - continue - } - stored = sql.NullString{String: string(b), Valid: true} - } - - result, err := insertSeen.ExecContext(ctx, record.Filename, int(status), res.File, primary, stored) + b, err := json.Marshal(res) if err != nil { printError(fmt.Sprintf("failed to record audit result for file %s: %s", res.File, err.Error())) continue } - - // Two files on disk can resolve to the same record, so which claims it must not depend on - // the order files were processed in. A file matching the record's own path wins over one - // matching through another directory, then the first path in sort order. The other file - // is treated as new - if n, _ := result.RowsAffected(); n == 0 { - var oldStatus int - var oldFile string - var oldPrimary bool - var oldResult sql.NullString - err := tx.QueryRowContext(ctx, "select status, disk_file, is_primary, result from temp.seen where filepath = ?", record.Filename).Scan(&oldStatus, &oldFile, &oldPrimary, &oldResult) - if err != nil { - printError(fmt.Sprintf("failed to read audit result for file %s: %s", res.File, err.Error())) - continue - } - - var old Result - wins := oldResult.Valid && (primary && !oldPrimary || primary == oldPrimary && res.File < oldFile) - if wins { - if err := json.Unmarshal([]byte(oldResult.String), &old); err != nil { - wins = false - } - // JSON replaces bytes which are not UTF-8, so the name is taken from disk_file - old.File = oldFile - } - if !wins { - newFileCandidates = append(newFileCandidates, res) - continue - } - - if _, err := tx.ExecContext(ctx, "update temp.seen set status = ?, disk_file = ?, is_primary = ?, result = ? where filepath = ?", int(status), res.File, primary, stored, record.Filename); err != nil { - printError(fmt.Sprintf("failed to record audit result for file %s: %s", res.File, err.Error())) - continue - } - if FileStatus(oldStatus) == FileMatched { - matched-- - } else { - filesModified-- - } - newFileCandidates = append(newFileCandidates, old) + if _, err := insertMatch.ExecContext(ctx, res.File, record.Filename, int(status), level, independent, string(b)); err != nil { + printError(fmt.Sprintf("failed to record audit result for file %s: %s", res.File, err.Error())) + continue } - - if status == FileMatched { - matched++ - } else { - filesModified++ + if !independent { + votes[level]++ } } + _ = insertMatch.Close() + + chosen := chooseLevel(votes) + matched, filesModified, unclaimed, err := claimSqliteMatches(ctx, tx, chosen) + if err != nil { + _ = tx.Rollback() + printError(fmt.Sprintf("failed to read audit results: %s", err.Error())) + return "", false + } + newFileCandidates = append(newFileCandidates, unclaimed...) // files which exist but could not be read are reported as such rather than as not found. A // record claimed by another file is reported for that file, so the unreadable file is listed - // on its own, as it is when it has no record - unreadable := map[string]bool{} + // on its own, as it is when it has no record or its record was moved to another file + unreadable := map[string]string{} + unreadableAt := map[string]int{} // unreadable file to the directory its record was found through var unreadableNew []string var failedList []string failedFiles.Range(func(key, _ any) bool { @@ -458,22 +621,32 @@ func doSqliteAudit(input chan Result) (string, bool) { }) sort.Strings(failedList) for _, f := range failedList { - filePath, _, ok, err := sqliteLookup(ctx, tx, bases, absFrom(cwd, f)) + abs := absFrom(cwd, f) + filePath, level, ok, err := sqliteLookup(ctx, tx, bases, abs) if err == nil && ok { + unreadableAt[abs] = level var claimed int err = tx.QueryRowContext(ctx, "select count(*) from temp.seen where filepath = ?", filePath).Scan(&claimed) ok = err == nil && claimed == 0 } if ok { - unreadable[filePath] = true + unreadable[filePath] = f } else { unreadableNew = append(unreadableNew, f) } } isUnreadable := func(filename string) bool { - if unreadable[filename] { + if _, ok := unreadable[filename]; ok { return true } + // another spelling of an unreadable file, which the lookup only returns one record for, + // through the directory its record was found through, so a path through another directory + // such as the working directory is not taken as another record's unreadable file + for level, base := range bases { + if at, ok := unreadableAt[absFrom(base, filename)]; ok && at == level { + return true + } + } for _, base := range bases { if isUnderFailedDir(absFrom(base, filename)) { return true @@ -482,7 +655,15 @@ func doSqliteAudit(input chan Result) (string, bool) { return false } - _ = insertSeen.Close() + duplicates, err := markSqliteDuplicates(ctx, tx, bases[max(chosen, 0)]) + if err != nil { + _ = tx.Rollback() + printError(fmt.Sprintf("failed to check audit database for duplicates: %s", err.Error())) + return "", false + } + if duplicates != 0 { + printWarn(fmt.Sprintf("audit database lists the same path more than once, only the first is used for each, duplicates: %d", duplicates)) + } if err := tx.Commit(); err != nil { printError(fmt.Sprintf("failed to commit audit results: %s", err.Error())) return "", false @@ -507,6 +688,7 @@ func doSqliteAudit(input chan Result) (string, bool) { f.blake2b_256, f.blake2b_512, f.blake3, f.sha3_224, f.sha3_256, f.sha3_384, f.sha3_512, f.ed2k, f.size, f.mtime, s.status, s.disk_file from file_hashes f left join temp.seen s on s.filepath = f.filepath +where f.rowid not in (select rid from temp.duplicates) order by f.filepath`) if err != nil { printError(fmt.Sprintf("failed to query audit database: %s", err.Error())) @@ -557,6 +739,9 @@ order by f.filepath`) if Verbose { fmt.Fprintf(stdout, "%v -> %v: File moved\n", record.Filename, newFileCandidates[i].File) } + if f, ok := unreadable[record.Filename]; ok { + unreadableNew = append(unreadableNew, f) + } break } } @@ -590,6 +775,7 @@ order by f.filepath`) fmt.Fprintf(stdout, "%v: File new\n", res.File) } // files on disk which are not in the database and could not be read + sort.Strings(unreadableNew) for _, f := range unreadableNew { fmt.Fprintf(stdout, "%v: File could not be read\n", f) } diff --git a/processor/audit_parser.go b/processor/audit_parser.go index dcd27e1..b522e2d 100644 --- a/processor/audit_parser.go +++ b/processor/audit_parser.go @@ -4,14 +4,19 @@ package processor import ( "bufio" + "bytes" "errors" "fmt" + "io/fs" "os" "path/filepath" "regexp" + "runtime" "sort" "strconv" "strings" + "sync" + "syscall" ) // AuditRecord represents a single file entry from an audit file, which can be @@ -22,6 +27,10 @@ type AuditRecord struct { Hashes map[string]string // hashit hash name to lowercase hex value Order int // position in the audit file, used to report in file order Matched bool + Conflict bool // the audit file lists different values of a hash for the file, so it cannot match + // Duplicate is a sum file line naming a file another line was checked against, so it is not + // reported on its own + Duplicate bool } // Auditor parses and holds an audit file which can then be used for audit purposes @@ -34,7 +43,9 @@ type Auditor struct { bases []string // absolute directories relative paths may be relative to, in priority order primaryBase string // directory relative paths were created relative to, empty for the working directory cwd string // working directory, looked up once as it is needed for every path - duplicates int // paths listed more than once, reported once parsing is done + duplicates []duplicateRecord // records dropped as listing the path of another, see restoreDuplicates + sumFile bool // a sum file, where every line for a path is checked + sameFile map[string][]*AuditRecord // sum file lines naming the same file through different paths, by its real path } type FileStatus int @@ -155,6 +166,7 @@ func NewAuditor(input string, auditFilename string) (*Auditor, error) { if isHashdeepFormat(input) { err = hdl.parseHashdeepFile(input) } else { + hdl.sumFile = true err = hdl.parseSumFile(input, auditFilename) } @@ -164,8 +176,8 @@ func NewAuditor(input string, auditFilename string) (*Auditor, error) { // copied elsewhere, where the invoked from directory no longer applies hdl.bases = auditBases(hdl.primaryBase, auditFilename, hdl.cwd) hdl.removeDuplicates() - if hdl.duplicates != 0 { - printWarn(fmt.Sprintf("audit file lists the same path more than once, only the first is used for each, duplicates: %d", hdl.duplicates)) + if conflicts := hdl.conflicts(); conflicts != 0 { + printWarn(fmt.Sprintf("audit file lists different hashes for the same path, which are reported as modified, paths: %d", conflicts)) } if err != nil { return nil, err @@ -197,7 +209,13 @@ func (hdl *Auditor) HashNames() []string { } func (hdl *Auditor) Count() int { - return len(hdl.records) + n := 0 + for _, r := range hdl.records { + if !r.Duplicate { + n++ + } + } + return n } // Records returns every record in the order it appeared in the audit file @@ -210,14 +228,61 @@ func (hdl *Auditor) Lookup(file string) *AuditRecord { return hdl.pathLookup[absFrom(hdl.cwd, file)] } -// LookupPrimary finds the record for a file on disk, and reports whether the file matched the -// record's own path rather than through another directory such as the audit file's -func (hdl *Auditor) LookupPrimary(file string) (*AuditRecord, bool) { +// LookupLevel finds the record for a file on disk, with the priority of the directory it matched +// through and whether the record names the same file through every directory, see baseLevel +func (hdl *Auditor) LookupLevel(file string) (*AuditRecord, int, bool) { r := hdl.Lookup(file) if r == nil { - return nil, false + return nil, 0, false + } + level, independent := baseLevel(hdl.bases, r.Filename, absFrom(hdl.cwd, file)) + return r, level, independent +} + +// baseLevel returns the priority of the first directory through which the path of a record names +// the absolute path of a file, and whether it is an absolute path, which names the same file +// through every directory. An audit is only ever matched through one directory, see chooseLevel. +// A relative path which happens to name the same file through every directory, such as ../y/a +// through sibling directories, is treated as relative, which can only report a move +func baseLevel(bases []string, p string, abs string) (int, bool) { + for i, base := range bases { + if absFrom(base, p) == abs { + return i, filepath.IsAbs(p) + } + } + return -1, filepath.IsAbs(p) +} + +// chooseLevel returns the directory an audit is matched through from the number of files on disk +// which matched a record through each, as matching each record through whichever directory finds it +// would let a file moved to where another directory places its record pass. The directory most +// files matched through is used, so a single file moved to where another directory places its +// record is the one reported, then the first in priority order. A record naming the same file +// through every directory does not count. It is -1 when no file counted +func chooseLevel(votes map[int]int) int { + chosen := -1 + for level, n := range votes { + if chosen == -1 || n > votes[chosen] || n == votes[chosen] && level < chosen { + chosen = level + } } - return r, hdl.primaryKey(r) == absFrom(hdl.cwd, file) + return chosen +} + +// judgingBases returns the directories through which records are judged to name the same path: the +// one the audit is matched through, or every directory when none was chosen, as when every file +// matched an absolute record nothing says which directory the relative records are relative to +func judgingBases(bases []string, chosen int) []string { + if chosen == -1 { + return bases + } + return bases[chosen : chosen+1] +} + +// keepsMatch reports whether a file matched through a directory is kept as matched once the +// directory the audit is matched through has been chosen, otherwise it is treated as new +func keepsMatch(chosen int, level int, independent bool) bool { + return independent || chosen == -1 || level == chosen } // primaryKey is the absolute path a record refers to using the directory paths were created @@ -278,6 +343,9 @@ func (hdl *Auditor) GetUnmatched() []*AuditRecord { // recordMatches compares every hash the record has, as well as size if known. A record must // share at least one hash with the result to be considered a match func recordMatches(r *AuditRecord, res Result) bool { + if r.Conflict { + return false + } if r.Size >= 0 && r.Size != res.Bytes { return false } @@ -297,12 +365,20 @@ func recordMatches(r *AuditRecord, res Result) bool { } // absFrom returns the absolute path p refers to, a relative path being resolved against the -// absolute directory base. Paths are only ever compared absolute, as a bare relative path such as -// x only means the same file when run from the same directory. This is done without asking the -// operating system for the working directory, as it is needed for every record and file +// absolute directory base, as it is compared. Paths are only ever compared absolute, as a bare +// relative path such as x only means the same file when run from the same directory, and through +// the working directory as it was reached, so the same file found through where a symlinked +// working directory really is, such as by an absolute path or .., is the same path func absFrom(base string, p string) string { + return logicalPath(absPath(base, p)) +} + +// absPath returns the absolute path p refers to, a relative path being resolved against the +// absolute directory base. This is done without asking the operating system for the working +// directory, as it is needed for every record and file +func absPath(base string, p string) string { if filepath.IsAbs(p) { - return filepath.Clean(p) + return osClean(p) } // a Windows path such as D:x is relative to the working directory of that drive if vol := filepath.VolumeName(p); vol != "" { @@ -318,7 +394,212 @@ func absFrom(base string, p string) string { if filepath.VolumeName(p) == "" && len(p) != 0 && os.IsPathSeparator(p[0]) { return filepath.Join(filepath.VolumeName(base), p) } - return filepath.Join(base, p) + if base == "" { + return osClean(p) + } + return osClean(base + string(filepath.Separator) + p) +} + +// dotDotResolved caches the directory the operating system resolves each path ending in .. to +var dotDotResolved sync.Map + +// osClean cleans a path, except that a path containing .. has everything up to its last .. resolved +// by the operating system. After a symlink .. leads to the parent of the directory the link points +// to, not the directory containing the link, so cleaning a/link/.. to a/ would name a different +// directory to the one the operating system reads. A path whose .. the operating system cannot +// resolve is returned as written, so it never names an existing file. Windows resolves .. by +// cleaning the path too +func osClean(path string) string { + clean := filepath.Clean(path) + if runtime.GOOS == "windows" { + return clean + } + end := lastDotDot(path) + if end == -1 { + return clean + } + + head := path[:end] + resolved, ok := dotDotResolved.Load(head) + if !ok { + resolved, _ = dotDotResolved.LoadOrStore(head, resolveDotDot(head)) + } + if resolved.(string) == "" { + // the OS cannot open it, so it is kept as written rather than cleaned into another path + return path + } + return filepath.Join(resolved.(string), path[end:]) +} + +// resolveDotDot returns the directory a path ending in .. names. It is cleaned as text when that +// names the same directory the OS opens, so paths through a symlinked directory such as the +// working directory are kept as written, and otherwise is where the OS resolves it to. An empty +// string is returned when it can never be opened +func resolveDotDot(head string) string { + if _, err := os.Stat(head); err == nil { + return sameOrReal(head) + } + + // the OS cannot open it, such as when the directory an audit file was created in has since + // been deleted. A directory which does not exist cannot be a symlink, so .. after it is removed + // as text, as it named when it was written, while .. after a symlink, a file or anything which + // cannot be checked means the path can never be opened + cur := "." + if filepath.IsAbs(head) { + cur = string(filepath.Separator) + } + missing := 0 + for _, c := range strings.Split(head, string(filepath.Separator)) { + switch { + case c == "" || c == ".": + case c == ".." && missing > 0: + cur = filepath.Dir(cur) + missing-- + case c == "..": + if _, err := os.Stat(cur + string(filepath.Separator) + ".."); err == nil { + if cur = sameOrReal(cur + string(filepath.Separator) + ".."); cur == "" { + return "" + } + } else if fi, err := os.Lstat(cur); err != nil || fi.Mode()&os.ModeSymlink != 0 || !fi.IsDir() { + return "" + } else { + cur = filepath.Dir(cur) + } + default: + cur = filepath.Join(cur, c) + if missing > 0 { + missing++ + } else if _, err := os.Lstat(cur); errors.Is(err, fs.ErrNotExist) && !errors.Is(err, syscall.ENOTDIR) { + missing = 1 + } else if err != nil { + // such as a directory which cannot be searched, which may hold a symlink + return "" + } + } + } + return cur +} + +// sameOrReal returns the path ending in .. cleaned as text when that is the same directory the OS +// opens, and otherwise where the OS resolves it to +func sameOrReal(head string) string { + fi, err := os.Stat(head) + if err != nil { + return "" + } + clean := filepath.Clean(head) + if cfi, err := os.Stat(clean); err == nil && os.SameFile(fi, cfi) { + return clean + } + if real, err := filepath.EvalSymlinks(head); err == nil { + return logicalPath(physicalAbs(real)) + } + return "" +} + +// logicalPath returns the path a path is compared as when the working directory, or a directory +// containing it, was reached through a symlink, so that every spelling of a file through them is +// the same. The path is first taken through where each of them really is, repeatedly as one can +// lead into another, then through the deepest of them containing it. The text is joined rather +// than cleaned, so a path kept as written because it cannot be opened stays as it is +func logicalPath(path string) string { + list := workingDirAncestors() + if len(list) == 0 { + return path + } + // bounded, as a symlink to a directory containing it means a path can be spelled with it + // repeated any number of times, each step removing one + for i := 0; i < 256; i++ { + changed := false + for _, d := range list { + if isUnder(path, d.dir) { + path = joinText(d.real, path[len(d.dir):]) + changed = true + break + } + } + if !changed { + break + } + } + for _, d := range list { + if isUnder(path, d.real) { + return joinText(d.dir, path[len(d.real):]) + } + } + return path +} + +// joinText joins a directory and the rest of a path inside it without cleaning it. The rest +// starts with a separator unless the directory is the root, which ends with one +func joinText(dir string, rest string) string { + sep := string(filepath.Separator) + rest = strings.TrimPrefix(rest, sep) + if rest == "" { + return dir + } + if strings.HasSuffix(dir, sep) { + return dir + rest + } + return dir + sep + rest +} + +// isUnder reports if path is the directory dir or inside it, comparing the text +func isUnder(path string, dir string) bool { + if !strings.HasPrefix(path, dir) { + return false + } + return len(path) == len(dir) || strings.HasSuffix(dir, string(filepath.Separator)) || os.IsPathSeparator(path[len(dir)]) +} + +type ancestor struct{ dir, real string } + +var ( + ancestorsOnce sync.Once + ancestorList []ancestor +) + +// workingDirAncestors returns the working directory and every directory containing it which was +// reached through a symlink, deepest first, with where each really is. It is looked up once, as +// it is needed for every path compared and the working directory does not change while running +func workingDirAncestors() []ancestor { + ancestorsOnce.Do(func() { + if runtime.GOOS == "windows" { + return + } + cwd := workingDir() + if cwd == "" { + return + } + // the working directory can be given with // or .. in it + for dir := filepath.Clean(cwd); ; dir = filepath.Dir(dir) { + if real := realPath(dir); real != "" && real != dir { + ancestorList = append(ancestorList, ancestor{dir: dir, real: real}) + } + if filepath.Dir(dir) == dir { + break + } + } + }) + return ancestorList +} + +// lastDotDot returns the index of the end of the last .. component in the path, or -1 +func lastDotDot(path string) int { + if !strings.Contains(path, "..") { + return -1 + } + end := -1 + start := 0 + for i := 0; i <= len(path); i++ { + if i == len(path) || os.IsPathSeparator(path[i]) { + if path[start:i] == ".." { + end = i + } + start = i + 1 + } + } + return end } // workingDir returns the working directory, or an empty string when it cannot be found such as @@ -351,7 +632,8 @@ func auditBases(primary string, auditFile string, cwd string) []string { if real := realPath(auditFile); real != "" { add(filepath.Dir(real)) } - add(filepath.Dir(auditFile)) + // resolved before taking its directory, as cleaning link/../m as text names another directory + add(filepath.Dir(absFrom(cwd, auditFile))) add(cwd) return bases } @@ -432,25 +714,196 @@ func (t auditFileTarget) matches(keys []string) bool { // removeDuplicates drops records for a path already listed, keeping the first, as otherwise the // duplicate is never matched and is reported as missing although the file exists func (hdl *Auditor) removeDuplicates() { - seen := map[string]bool{} + seen := map[string]*AuditRecord{} var records []*AuditRecord for _, r := range hdl.records { // compare the resolved path, so the same file listed by relative and absolute path is a // duplicate too key := hdl.primaryKey(r) - if seen[key] { + if hdl.sumFile { + // only lines naming the same path through every directory, as a relative line can be + // found through the sum file's directory while an absolute one cannot, see groupSameFile + key = strings.Join(hdl.recordKeys(r), "\x00") + } + if first, ok := seen[key]; ok { + // md5sum -c checks every line, so the hashes of a sum file are merged + if hdl.sumFile { + first.Conflict = first.Conflict || r.Conflict + for name, value := range r.Hashes { + mergeSumHash(first, name, value) + } + } else { + hdl.duplicates = append(hdl.duplicates, duplicateRecord{record: r, first: first}) + } continue } - seen[key] = true + seen[key] = r records = append(records, r) } - if dupes := len(hdl.records) - len(records); dupes != 0 { - hdl.duplicates += dupes + if len(records) != len(hdl.records) { hdl.records = nil for _, r := range records { hdl.addRecord(r) } } + if hdl.sumFile { + hdl.groupSameFile() + } +} + +// duplicateRecord is a record dropped as listing the path of the first record listing it +type duplicateRecord struct { + record *AuditRecord + first *AuditRecord +} + +// restoreDuplicates returns to the audit each dropped record which names another path than the +// record it duplicates through the directory the audit is matched through, such as an absolute +// path into a tree which was copied elsewhere with the audit file, by the path it names there +func (hdl *Auditor) restoreDuplicates(chosen int) map[string]*AuditRecord { + bases := judgingBases(hdl.bases, chosen) + restored := map[string]*AuditRecord{} + var kept []duplicateRecord + for _, d := range hdl.duplicates { + same := false + for _, base := range bases { + same = same || absFrom(base, d.record.Filename) == absFrom(base, d.first.Filename) + } + if same { + kept = append(kept, d) + continue + } + k := absFrom(bases[0], d.record.Filename) + hdl.addRecord(d.record) + for name, v := range d.record.Hashes { + hdl.hashLookup[name+":"+v] = append(hdl.hashLookup[name+":"+v], d.record) + } + if restored[k] == nil { + restored[k] = d.record + } + } + hdl.duplicates = kept + return restored +} + +// warnDuplicates reports the records dropped as listing the path of another +func (hdl *Auditor) warnDuplicates() { + if len(hdl.duplicates) != 0 { + printWarn(fmt.Sprintf("audit file lists the same path more than once, only the first is used for each, duplicates: %d", len(hdl.duplicates))) + } +} + +// groupSameFile groups the lines of a sum file which name the same file through different paths. +// A sum file has no directory its paths were created relative to, so lines can name the same file +// through the sum file's directory but not through the working directory, or through a symlinked +// directory. Each line is kept, as its own path may be the one which is scanned, and a line is only +// not reported on its own when another line was checked against the same file. Lines listing +// different values of a hash for the file can never match +func (hdl *Auditor) groupSameFile() { + // the records naming each path through any directory, so most records need no lookup on disk + counts := make(map[string]int, len(hdl.records)*len(hdl.bases)) + for _, r := range hdl.records { + for _, k := range hdl.recordKeys(r) { + counts[k]++ + } + } + + groups := map[string][]*AuditRecord{} + for _, r := range hdl.records { + keys := hdl.recordKeys(r) + for _, k := range keys { + if counts[k] > 1 { + // the first file it names, by where it really is, as that is the file it is checked + // against + for _, k := range keys { + if fi, err := os.Stat(k); err == nil && fi.Mode().IsRegular() { + real := realPath(k) + groups[real] = append(groups[real], r) + break + } + } + break + } + } + } + + hdl.sameFile = map[string][]*AuditRecord{} + for real, group := range groups { + if len(group) < 2 { + continue + } + hdl.sameFile[real] = group + values := map[string]string{} + conflict := false + for _, r := range group { + conflict = conflict || r.Conflict + for name, v := range r.Hashes { + if existing, ok := values[name]; ok && existing != v { + conflict = true + } + values[name] = v + } + } + // every line is checked with every hash listed for the file, as which line is checked + // against it decides the others are duplicates + for _, r := range group { + r.Conflict = r.Conflict || conflict + for name, v := range values { + if _, ok := r.Hashes[name]; !ok { + r.Hashes[name] = v + } + } + } + } +} + +// settleSameFile marks the lines of a sum file naming a file which another line naming it was +// checked against as duplicates, so they are not reported as missing or paired with another file. +// A line must name the file through the directory the audit is matched through, as a line naming +// it only through another directory names a file which was not checked, see chooseLevel, unless +// none was chosen, see judgingBases. Before +// moves are found a line must have been checked against the file itself, not a file found through +// another directory, and after a line moved with the file no longer where it was, when a line +// must name the path the moved line does +func (hdl *Auditor) settleSameFile(checked func(*AuditRecord) (string, FileStatus, bool), afterMoves bool, chosen int) { + bases := judgingBases(hdl.bases, chosen) + for real, group := range hdl.sameFile { + var movedFrom []string + settled := false + if afterMoves { + if _, err := os.Stat(real); err != nil { + for _, r := range group { + if _, status, ok := checked(r); ok && status == FileMoved { + for _, base := range bases { + movedFrom = append(movedFrom, absFrom(base, r.Filename)) + } + } + } + } + } else { + for _, r := range group { + if file, _, ok := checked(r); ok && realPath(file) == real { + settled = true + } + } + } + if !settled && len(movedFrom) == 0 { + continue + } + for _, r := range group { + if _, _, ok := checked(r); ok { + continue + } + for _, base := range bases { + k := absFrom(base, r.Filename) + if settled && realPath(k) == real || contains(movedFrom, k) { + r.Matched = true + r.Duplicate = true + break + } + } + } + } } // isEmptyRecord reports if the record describes an empty file, by size or when the size is not @@ -512,15 +965,26 @@ func (hdl *Auditor) buildLookups() { func (hdl *Auditor) parseHashdeepFile(input string) error { scanner := bufio.NewScanner(strings.NewReader(input)) scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024) + scanner.Split(scanLinesKeepCR) var header []string filenameIdx := -1 lineNo := 0 + // a filename can end with \r, so one is only removed when the file has windows line endings, + // which the HASHDEEP line starting each section shows + crlf := false + for scanner.Scan() { lineNo++ + line := scanner.Text() + if strings.HasPrefix(line, "%%%% HASHDEEP") { + crlf = strings.HasSuffix(line, "\r") + } // filenames can start or end with spaces so only remove line endings - line := strings.TrimRight(scanner.Text(), "\r") + if crlf { + line = strings.TrimSuffix(line, "\r") + } if strings.TrimSpace(line) == "" { continue @@ -550,7 +1014,8 @@ func (hdl *Auditor) parseHashdeepFile(input string) error { // as relative paths in the file are relative to it if strings.HasPrefix(line, "#") { if dir, ok := strings.CutPrefix(line, "## Invoked from: "); ok && hdl.primaryBase == "" { - hdl.primaryBase = strings.TrimSpace(dir) + // a directory name can start or end with spaces + hdl.primaryBase = dir } continue } @@ -620,6 +1085,41 @@ func splitHashdeepLine(line string, columns int, filenameIdx int) ([]string, err return fields, nil } +// scanLinesKeepCR splits lines like bufio.ScanLines, but leaves any \r before the newline in place +func scanLinesKeepCR(data []byte, atEOF bool) (int, []byte, error) { + if atEOF && len(data) == 0 { + return 0, nil, nil + } + if i := bytes.IndexByte(data, '\n'); i >= 0 { + return i + 1, data[:i], nil + } + if atEOF { + return len(data), data, nil + } + return 0, nil, nil +} + +// conflicts counts the records with different values listed for one of their hashes +func (hdl *Auditor) conflicts() int { + n := 0 + for _, r := range hdl.records { + if r.Conflict { + n++ + } + } + return n +} + +// mergeSumHash adds a hash from a sum file line to the record for its file, a different value +// for a hash it already has meaning the file can never match +func mergeSumHash(r *AuditRecord, name string, value string) { + if existing, ok := r.Hashes[name]; ok && existing != value { + r.Conflict = true + return + } + r.Hashes[name] = value +} + // parseSumFile parses the output of md5sum, sha256sum and similar tools, including hashit's // sum format. Both the GNU "hash filename" and BSD "MD5 (filename) = hash" styles are accepted func (hdl *Auditor) parseSumFile(input string, auditFilename string) error { @@ -628,7 +1128,6 @@ func (hdl *Auditor) parseSumFile(input string, auditFilename string) error { extHashes := sumExtensions[strings.ToLower(filepath.Ext(auditFilename))] byFile := map[string]*AuditRecord{} - duplicateSumLines := 0 improper := 0 for scanner.Scan() { @@ -656,21 +1155,15 @@ func (hdl *Auditor) parseSumFile(input string, auditFilename string) error { byFile[filename] = r hdl.addRecord(r) } - // the same path listed again with a different value of the same hash keeps the first, the - // same as a path listed twice in a hashdeep file - if existing, ok := r.Hashes[name]; ok && existing != value { - duplicateSumLines++ - continue - } - r.Hashes[name] = value + // md5sum -c checks every line, so the same path listed again with a different value of the + // same hash can never match + mergeSumHash(r, name, value) } if err := scanner.Err(); err != nil { return err } - hdl.duplicates += duplicateSumLines - if improper != 0 { // a file such as text or json output has no valid lines, and is not an audit file at all if len(hdl.records) == 0 { diff --git a/processor/audit_test.go b/processor/audit_test.go index eb6861d..757de26 100644 --- a/processor/audit_test.go +++ b/processor/audit_test.go @@ -6,19 +6,34 @@ import ( "os" "path/filepath" "runtime" + "strings" "testing" ) func TestAbsFrom(t *testing.T) { + dir := realPath(t.TempDir()) + if err := os.MkdirAll(filepath.Join(dir, "srv", "media", "sub"), 0755); err != nil { + t.Fatal(err) + } + srv := filepath.Join(dir, "srv") cases := []struct{ base, p, want string }{ - {"/srv/media", "a.txt", "/srv/media/a.txt"}, - {"/srv/media", "./sub/../a.txt", "/srv/media/a.txt"}, - {"/srv/media", "../other/a.txt", "/srv/other/a.txt"}, - {"/srv/media", "/abs/./a.txt", "/abs/a.txt"}, + {srv + "/media", "a.txt", srv + "/media/a.txt"}, + {srv + "/media", "./sub/../a.txt", srv + "/media/a.txt"}, + {srv + "/media", "../other/a.txt", srv + "/other/a.txt"}, + {srv + "/media", "/abs/./a.txt", "/abs/a.txt"}, + // a directory which no longer exists, such as the one an audit file was created in + {srv + "/gone", "../media/a.txt", srv + "/media/a.txt"}, } for _, c := range cases { - if got := absFrom(c.base, c.p); got != filepath.FromSlash(c.want) { - t.Errorf("%q %q: expected %q got %q", c.base, c.p, c.want, got) + if runtime.GOOS == "windows" && c.want[0] == '/' { + continue // takes the base's drive, see TestAbsFromWindows + } + want := filepath.FromSlash(c.want) + if runtime.GOOS == "windows" { + want = filepath.Clean(want) + } + if got := absFrom(filepath.FromSlash(c.base), filepath.FromSlash(c.p)); got != want { + t.Errorf("%q %q: expected %q got %q", c.base, c.p, want, got) } } } @@ -185,7 +200,6 @@ func TestIsDirectSpelling(t *testing.T) { "a": true, "sub/a": true, "./sub/a": true, - "../a": true, "/abs/a": runtime.GOOS != "windows", // \abs\a has no drive on windows "sub//a": false, "sub/./a": false, @@ -195,6 +209,11 @@ func TestIsDirectSpelling(t *testing.T) { "": false, "sub/a/": false, "././sub": false, + "../a": false, + "./../a": false, + "..": false, + ".//a": false, + "..a": true, } for p, want := range cases { if got := isDirectSpelling(filepath.FromSlash(p)); got != want { @@ -202,3 +221,86 @@ func TestIsDirectSpelling(t *testing.T) { } } } + +func TestOsClean(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("windows resolves .. by cleaning the path") + } + dir := realPath(t.TempDir()) + if err := os.MkdirAll(filepath.Join(dir, "real", "d", "a..b"), 0755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join(dir, "real", "d"), filepath.Join(dir, "link")); err != nil { + t.Skip("symlinks not supported") + } + if err := os.Symlink(dir, filepath.Join(dir, "self")); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "real", "file"), nil, 0600); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(dir, "locked"), 0755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join(dir, "real", "d"), filepath.Join(dir, "locked", "lk")); err != nil { + t.Fatal(err) + } + if err := os.Chmod(filepath.Join(dir, "locked"), 0); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(filepath.Join(dir, "locked"), 0755) }) + if err := os.Symlink(filepath.Join(dir, "gone"), filepath.Join(dir, "dangling")); err != nil { + t.Fatal(err) + } + cases := map[string]string{ + "link/../x": "real/x", + "link/../d/a": "real/d/a", + "real/../a": "a", + "real/./d//a": "real/d/a", + "link/../../a": "a", + "real/d/../..": "", + "..notes/a": "..notes/a", + "link/a..b/../": "link", + // a symlink which cleaning names the same directory as the OS reads is kept as written + "self/real/../a": "self/a", + // a directory which no longer exists cannot have been a symlink, so is cleaned as text + "gone/../a": "a", + "gone/x/../../a": "a", + "real/gone/../../a": "a", + "link/gone/../../a": "real/a", + "real/d/gone/../../..": "", + // .. after a symlink or file which cannot be followed is kept as written + "dangling/../a": "dangling/../a", + "dangling/x/../../a": "dangling/x/../../a", + "real/file/../a": "real/file/../a", + "real/file/x/../../a": "real/file/x/../../a", + // a directory which cannot be searched may hold a symlink + "locked/lk/../a": "locked/lk/../a", + } + for p, want := range cases { + path := filepath.Join(dir, "") + "/" + p + expected := filepath.Join(dir, want) + if strings.Contains(want, "..") { + expected = path + } + if got := osClean(path); got != expected { + t.Errorf("%q: expected %q got %q", p, expected, got) + } + } +} + +func TestJoinText(t *testing.T) { + cases := []struct{ dir, rest, want string }{ + {"/a/b", "/c", "/a/b/c"}, + {"/a/b", "c", "/a/b/c"}, + {"/", "/c", "/c"}, + {"/", "c", "/c"}, + {"/a", "", "/a"}, + {"/a", "/x/../y", "/a/x/../y"}, + } + for _, c := range cases { + if got := joinText(filepath.FromSlash(c.dir), filepath.FromSlash(c.rest)); got != filepath.FromSlash(c.want) { + t.Errorf("%q %q: expected %q got %q", c.dir, c.rest, c.want, got) + } + } +} diff --git a/processor/file.go b/processor/file.go index 6adf223..28302da 100644 --- a/processor/file.go +++ b/processor/file.go @@ -10,6 +10,7 @@ import ( "path/filepath" "regexp" "strings" + "syscall" "github.com/boyter/gocodewalker" ) @@ -64,13 +65,36 @@ func realPath(path string) string { if err != nil { return "" } - abs, err := filepath.Abs(real) + return physicalAbs(real) +} + +// physicalAbs returns the absolute path of a path with its symlinks already resolved, such as +// ../../x. filepath.Abs joins it to the working directory as the shell named it, which when that +// was reached through a symlink is not where the operating system resolves .. to, so the working +// directory as the operating system has it is used instead +func physicalAbs(resolved string) string { + if filepath.IsAbs(resolved) { + return filepath.Clean(resolved) + } + if cwd, err := syscall.Getwd(); err == nil { + return filepath.Join(cwd, resolved) + } + abs, err := filepath.Abs(resolved) if err != nil { return "" } return abs } +// osAbs returns the absolute path the operating system resolves path to, for opening a file by +// an absolute path, such as a SQLite database +func osAbs(path string) (string, error) { + if real := realPath(path); real != "" { + return real, nil + } + return filepath.Abs(path) +} + // walkDirectoryWithIgnore walks the directory sending every file found to output, with // prefix added to the start of each path func walkDirectoryWithIgnore(toWalk string, prefix string, output chan fileJob) { @@ -100,7 +124,7 @@ func walkDirectoryWithIgnore(toWalk string, prefix string, output chan fileJob) // unreadable rather than missing var pathErr *fs.PathError if errors.As(err, &pathErr) { - if abs, aerr := filepath.Abs(pathErr.Path); aerr == nil { + if abs := absFrom(workingDir(), pathErr.Path); filepath.IsAbs(abs) { failedDirs.Store(abs, true) } } diff --git a/processor/formatters.go b/processor/formatters.go index 59b77b9..1a45386 100644 --- a/processor/formatters.go +++ b/processor/formatters.go @@ -192,10 +192,7 @@ const ( // isDuplicateFile reports if the file has already been seen, recording it if not func isDuplicateFile(seen map[string]bool, file string) bool { - key, err := filepath.Abs(file) - if err != nil { - key = filepath.Clean(file) - } + key := absFrom(workingDir(), file) if seen[key] { return true } @@ -213,7 +210,10 @@ func auditFailed(modified, moved, newFiles, missing int) bool { if moved > 0 && !AllowMoved { return true } - return modified > 0 || newFiles > 0 || missing > 0 + if newFiles > 0 && !AllowNew { + return true + } + return modified > 0 || missing > 0 } func doAudit(input chan Result) (string, bool) { @@ -231,15 +231,16 @@ func doAudit(input chan Result) (string, bool) { outcomes := map[*AuditRecord]outcome{} var newFileCandidates []Result - // Two files on disk can resolve to the same record, so decide which claims it once every file - // has arrived, so the result does not depend on the order files were processed in. A file - // matching the record's own path wins over one matching through another directory, then the - // first path in sort order + // The directory the audit is matched through is chosen once every file has arrived, see + // chooseLevel, so files matching a record are held until then type claim struct { - res Result - primary bool + res Result + r *AuditRecord + level int + independent bool } - claims := map[*AuditRecord]claim{} + var found []claim + votes := map[int]int{} seen := map[string]bool{} for res := range input { @@ -249,25 +250,57 @@ func doAudit(input chan Result) (string, bool) { } examinedCount++ - r, primary := auditor.LookupPrimary(res.File) + r, level, independent := auditor.LookupLevel(res.File) if r == nil { newFileCandidates = append(newFileCandidates, res) continue } + found = append(found, claim{res: res, r: r, level: level, independent: independent}) + if !independent { + votes[level]++ + } + } + chosen := chooseLevel(votes) - existing, ok := claims[r] + // Two files on disk can resolve to the same record, so which claims it does not depend on the + // order files were processed in. A file matching through a directory earlier in priority order + // wins, being the record's own path before another directory, then the first path in sort order + claims := map[*AuditRecord]claim{} + for _, c := range found { + if !keepsMatch(chosen, c.level, c.independent) { + newFileCandidates = append(newFileCandidates, c.res) + continue + } + existing, ok := claims[c.r] if !ok { - claims[r] = claim{res: res, primary: primary} + claims[c.r] = c continue } - if primary != existing.primary && primary || primary == existing.primary && res.File < existing.res.File { - claims[r] = claim{res: res, primary: primary} + if c.level < existing.level || c.level == existing.level && c.res.File < existing.res.File { + claims[c.r] = c newFileCandidates = append(newFileCandidates, existing.res) } else { - newFileCandidates = append(newFileCandidates, res) + newFileCandidates = append(newFileCandidates, c.res) } } + // a record dropped as listing the path of another names another file through the directory the + // audit is matched through, so is audited on its own + if restored := auditor.restoreDuplicates(chosen); len(restored) != 0 { + var remaining []Result + for _, res := range newFileCandidates { + if r := restored[absFrom(auditor.cwd, res.File)]; r != nil { + if _, ok := claims[r]; !ok { + claims[r] = claim{res: res, r: r, level: max(chosen, 0)} + continue + } + } + remaining = append(remaining, res) + } + newFileCandidates = remaining + } + auditor.warnDuplicates() + for r, c := range claims { r.Matched = true if recordMatches(r, c.res) { @@ -279,6 +312,12 @@ func doAudit(input chan Result) (string, bool) { } } + checked := func(r *AuditRecord) (string, FileStatus, bool) { + o, ok := outcomes[r] + return o.file, o.status, ok + } + auditor.settleSameFile(checked, false, chosen) + // With every file on disk accounted for, anything new may be a known file which was // moved or renamed, which we identify by matching size and hashes against unmatched records var newFiles []Result @@ -292,6 +331,7 @@ func doAudit(input chan Result) (string, bool) { newFiles = append(newFiles, res) } } + auditor.settleSameFile(checked, true, chosen) // files which exist but could not be read are reported as such rather than as not found unreadable := map[*AuditRecord]bool{} @@ -323,6 +363,9 @@ func doAudit(input chan Result) (string, bool) { filesMissing := 0 for _, r := range auditor.Records() { o, ok := outcomes[r] + if r.Duplicate { + continue + } if !ok { filesMissing++ if Verbose { @@ -853,7 +896,7 @@ func contains(list []string, v string) bool { func connectSqliteDb(pathName string) (*sql.DB, error) { // build a file URI so a path containing ? or # is not taken as the start of parameters - abs, err := filepath.Abs(pathName) + abs, err := osAbs(pathName) if err != nil { return nil, err } diff --git a/processor/processor.go b/processor/processor.go index 676a22a..981ccec 100644 --- a/processor/processor.go +++ b/processor/processor.go @@ -59,6 +59,10 @@ var Absolute = false // AllowMoved allows an audit to pass when known files have moved, so long as they are unmodified var AllowMoved = false +// AllowNew allows an audit to pass when there are files which are not in the audit file, so only +// the files it lists are verified, as md5sum -c does +var AllowNew = false + // If data is being piped in using stdin var StandardInput = false @@ -100,8 +104,8 @@ func addSkipFile(path string, byIdentity bool, sqlite bool) { if p == "" { continue } - abs, err := filepath.Abs(p) - if err != nil { + abs := absFrom(workingDir(), p) + if !filepath.IsAbs(abs) { continue } for _, suffix := range suffixes { @@ -155,8 +159,7 @@ func shouldSkipFile(path string) bool { if len(skipFiles) == 0 { return false } - abs, err := filepath.Abs(path) - if err == nil && skipFiles[abs] { + if skipFiles[absFrom(workingDir(), path)] { return true } @@ -293,6 +296,9 @@ func Process() { if AllowMoved && AuditFile == "" { printWarn("--allow-moved only applies when auditing with --audit, ignoring flag") } + if AllowNew && AuditFile == "" { + printWarn("--allow-new only applies when auditing with --audit, ignoring flag") + } // Interrupting removes any temporary output, and exits with the conventional code for the signal removeOutputTempOnSignal() @@ -401,17 +407,17 @@ func Process() { go func() { // Check if the paths or files added exist and inform the user if they don't for _, f := range DirFilePaths { - fp := filepath.Clean(f) + fp, cleaned := cleanPathArg(f) fi, err := os.Stat(fp) // keep a leading ./ the user supplied as hashdeep and md5sum do, so that our // output matches theirs when run the same way prefix := "" if Absolute { - if abs, err := filepath.Abs(fp); err == nil { + if abs := absPath(workingDir(), fp); filepath.IsAbs(abs) { fp = abs } - } else if !defaultPath { + } else if !defaultPath && cleaned { prefix = dotPrefix(f, fp) } @@ -455,7 +461,7 @@ func Process() { continue } if Absolute { - if abs, err := filepath.Abs(line); err == nil { + if abs := absPath(workingDir(), line); filepath.IsAbs(abs) { line = abs } } @@ -874,6 +880,31 @@ func installOutput() error { return nil } +// cleanPathArg cleans a supplied path, reporting false when cleaning it would name a different +// file, such as link/.. when link is a symlink, in which case it is resolved by the operating +// system instead, as files are found by joining names to it which would clean it +func cleanPathArg(path string) (string, bool) { + clean := filepath.Clean(path) + end := lastDotDot(path) + if clean == path || end == -1 { + return clean, true + } + if _, err := os.Stat(path); err != nil { + // reported for the path as supplied, rather than reading what cleaning it names + return path, false + } + // resolved as paths in audit files are, up to the last .., so a symlink after it is walked + // as supplied + head := resolveDotDot(path[:end]) + if head == "" { + return path, false + } + if head == filepath.Clean(path[:end]) { + return clean, true + } + return filepath.Join(head, path[end:]), false +} + // dotPrefix returns "./" when the supplied path started with it, or was the current directory, // and the cleaned path does not already start with it. Paths which are absolute or leave the // current directory such as "./../a" are returned as cleaned without a prefix diff --git a/test-all.sh b/test-all.sh index e565cb1..423f917 100755 --- a/test-all.sh +++ b/test-all.sh @@ -867,7 +867,7 @@ check "two files matching one record are not both counted test" \ mkdir -p "$AUDITDIR/r6/dupsum" echo a > "$AUDITDIR/r6/dupsum/a" (cd "$AUDITDIR/r6/dupsum" && md5sum a > ../dupsum.md5 && echo "00000000000000000000000000000000 a" >> ../dupsum.md5) -check "sum file listing a path twice uses the first test" "cd '$AUDITDIR/r6/dupsum' && '$HASHIT' -a ../dupsum.md5 . 2>/dev/null | grep -q 'Audit passed'" +check "sum file listing a path twice with different hashes is modified test" "cd '$AUDITDIR/r6/dupsum' && '$HASHIT' -a ../dupsum.md5 . 2>/dev/null | grep -q 'Files modified: 1' && ! md5sum -c ../dupsum.md5 > /dev/null 2>&1" check "format with audit warns test" "'$HASHIT' -f json -a '$AUDITDIR/r6/empty.txt' '$AUDITDIR/r6/empty' 2>&1 >/dev/null | grep -q 'format is ignored'" # round 7 @@ -988,6 +988,404 @@ if unshare -r -m true 2> /dev/null; then check "sqlite database which cannot be written in full is discarded test" "cd '$AUDITDIR/r9/full' && unshare -r -m sh -c \"mount -t tmpfs -o size=300k tmpfs mnt && ! '$HASHIT' -f sqlite -o mnt/n.db src > out.txt 2>&1 && [ -z \\\"\\\$(ls -A mnt)\\\" ]\" && ! grep -q 'results written' out.txt" fi +# round 10 +mkdir -p "$AUDITDIR/r10/q/t/sub/deep" +echo a > "$AUDITDIR/r10/q/t/a" +ln -s t/sub/deep "$AUDITDIR/r10/q/j" +(cd "$AUDITDIR/r10/q/j" && "$HASHIT" -f sqlite -o ../../m.db ../.. > /dev/null) +check "sqlite output through a symlinked working directory and .. test" "[ \"\$(sqlite3 '$AUDITDIR/r10/q/t/m.db' 'select count(*) from file_hashes')\" == 1 ] && ! ls -a '$AUDITDIR/r10' | grep -q hashit.tmp" +echo changed > "$AUDITDIR/r10/q/t/a" +"$HASHIT" -f sqlite -o "$AUDITDIR/r10/m.db" "$AUDITDIR/r10/q/t/a" > /dev/null +check "sqlite audit through a symlinked working directory and .. opens the right database test" "cd '$AUDITDIR/r10/q/j' && '$HASHIT' -a ../../m.db '$AUDITDIR/r10/q/t' > /dev/null; [ \$? -eq 1 ]" +mkdir -p "$AUDITDIR/r10/u/sub/deep" +echo a > "$AUDITDIR/r10/u/a" +echo b > "$AUDITDIR/r10/u/sub/b" +(cd "$AUDITDIR/r10/u/sub" && "$HASHIT" -f sqlite -o "$AUDITDIR/r10/u.db" .. > /dev/null) +check "sqlite database generated with .. audits test" "cd '$AUDITDIR/r10/u/sub' && '$HASHIT' -a '$AUDITDIR/r10/u.db' .. | grep -q 'Audit passed'" +mkdir -p "$AUDITDIR/r10/trail /x" +echo q > "$AUDITDIR/r10/trail /x/f" +(cd "$AUDITDIR/r10/trail " && "$HASHIT" -f hashdeep x > ../trail.hd) +check "hashdeep invoked from a directory ending in a space test" "cd / && '$HASHIT' -a '$AUDITDIR/r10/trail.hd' '$AUDITDIR/r10/trail /x' | grep -q 'Audit passed'" +mkdir -p "$AUDITDIR/r10/cr" +echo 1 > "$AUDITDIR/r10/cr/$(printf 'cr\r')" +(cd "$AUDITDIR/r10" && "$HASHIT" -f hashdeep cr > cr.hd) +check "hashdeep filename ending in a carriage return test" "cd '$AUDITDIR/r10' && '$HASHIT' -a cr.hd cr | grep -q 'Audit passed' && sed 's/\$/\r/' cr.hd > crlf.hd && '$HASHIT' -a crlf.hd cr | grep -q 'Audit passed'" + +# round 11 +mkdir -p "$AUDITDIR/r11/FP/real/d" "$AUDITDIR/r11/FP/d" "$AUDITDIR/r11/m" +printf a > "$AUDITDIR/r11/FP/real/d/a" +printf a > "$AUDITDIR/r11/FP/d/a" +ln -s real/d "$AUDITDIR/r11/FP/link" +(cd "$AUDITDIR/r11/FP" && "$HASHIT" -f hashdeep -o ../m/d.hd d > /dev/null && "$HASHIT" -f sqlite -o ../m/d.db d > /dev/null) +printf changed > "$AUDITDIR/r11/FP/d/a" +check ".. from a symlinked working directory audits the directory read test" "cd '$AUDITDIR/r11/FP/link' && ! '$HASHIT' -a ../../m/d.hd ../d > /dev/null && ! '$HASHIT' -a ../../m/d.db ../d > /dev/null" +check "--absolute with .. from a symlinked working directory test" "cd '$AUDITDIR/r11/FP/link' && '$HASHIT' --absolute -f sum -c md5 ../d | grep -q '/r11/FP/real/d/a\$'" +mkdir -p "$AUDITDIR/r11/t" "$AUDITDIR/r11/other/x" +echo a > "$AUDITDIR/r11/t/a" +echo o > "$AUDITDIR/r11/other/o" +ln -s ../other/x "$AUDITDIR/r11/t/sl" +check "a symlink followed by .. hashes the directory the operating system reads test" "cd '$AUDITDIR/r11' && '$HASHIT' -f sum -c md5 t/sl/.. | grep -q 'other/o\$'" +mkdir -p "$AUDITDIR/r11/s/sub" +echo a > "$AUDITDIR/r11/s/plain" +echo b > "$AUDITDIR/r11/s/sub/b" +(cd "$AUDITDIR/r11/s" && md5sum ./plain sub/b > ../dup.txt && echo "0000000000000000000000000000000000000000 plain" >> ../dup.txt) +check "every line of a sum file listing a file twice is checked test" "cd '$AUDITDIR/r11/s' && ! '$HASHIT' -a ../dup.txt . > /dev/null 2>&1 && ! sha1sum -c ../dup.txt > /dev/null 2>&1" +(cd "$AUDITDIR/r11/s" && md5sum ./plain sub/b > ../both.txt && sha1sum plain >> ../both.txt) +check "a sum file listing a file with two hashes passes test" "cd '$AUDITDIR/r11/s' && '$HASHIT' -a ../both.txt . | grep -q 'Audit passed'" + +# round 12 +mkdir -p "$AUDITDIR/r12/R/T/x" "$AUDITDIR/r12/m" +echo f > "$AUDITDIR/r12/R/T/f" +ln -s R "$AUDITDIR/r12/L" +(cd "$AUDITDIR/r12/L/T/x" && "$HASHIT" -f hashdeep -o ../../../m/up.hd .. > /dev/null && "$HASHIT" -f sqlite -o ../../../m/up.db .. > /dev/null) +for AUDITFILE in up.hd up.db; do + check "manifest made with .. audited with . from a symlinked working directory $AUDITFILE test" \ + "cd '$AUDITDIR/r12/L/T' && '$HASHIT' -a ../../m/$AUDITFILE . | grep -q 'Audit passed'" +done +mkdir -p "$AUDITDIR/r12/g" +echo f > "$AUDITDIR/r12/g/f" +ln -s gone "$AUDITDIR/r12/g/link" +(cd "$AUDITDIR/r12/g" && "$HASHIT" -f hashdeep f | sed 's/,f$/,link\/..\/f/' > ../g.hd && md5sum f | sed 's/ f$/ link\/..\/f/' > ../g.md5) +for AUDITFILE in g.hd g.md5; do + check "record through a dangling symlink and .. does not match another file $AUDITFILE test" \ + "cd '$AUDITDIR/r12/g' && ! '$HASHIT' -a ../$AUDITFILE f > /dev/null 2>&1 && ! md5sum -c ../g.md5 > /dev/null 2>&1" +done +mkdir -p "$AUDITDIR/r11/tgt" +echo g > "$AUDITDIR/r11/tgt/g" +ln -s ../tgt "$AUDITDIR/r11/other/ln" +check "a symlink after .. is walked as supplied test" "cd '$AUDITDIR/r11' && '$HASHIT' -f sum -c md5 t/sl/../ln | grep -q 'other/ln/g\$'" +mkdir -p "$AUDITDIR/r12/sa/t" +echo a > "$AUDITDIR/r12/sa/t/a" && echo b > "$AUDITDIR/r12/sa/t/b" +(cd "$AUDITDIR/r12/sa/t" && md5sum a b ../t/a "$PWD/a" > s.md5) +check "sum file listing a file twice audited from outside its directory test" "cd '$AUDITDIR/r12/sa' && '$HASHIT' -a t/s.md5 t | grep -q 'Audit passed'" +mkdir -p "$AUDITDIR/r12/sb/t" +echo a > "$AUDITDIR/r12/sb/t/a" && echo c > "$AUDITDIR/r12/sb/t/c" +(cd "$AUDITDIR/r12/sb/t" && { md5sum c | sed 's/ c$/ a/'; md5sum "$PWD/a"; } > s.md5) +check "conflicting sum lines audited from outside its directory are not a move test" \ + "cd '$AUDITDIR/r12/sb' && ! '$HASHIT' --allow-moved -a t/s.md5 t > /dev/null 2>&1 && '$HASHIT' -a t/s.md5 t 2>&1 | grep -q 'different hashes'" +mkdir -p "$AUDITDIR/r12/u" +echo u > "$AUDITDIR/r12/u/u" +(cd "$AUDITDIR/r12/u" && "$HASHIT" -f sqlite -o ../u.db . > /dev/null) +sqlite3 "$AUDITDIR/r12/u.db" "insert into file_hashes select 'x/../u', crc32, xxhash64, md4, md5, sha1, sha224, sha256, sha384, sha512, blake2b_256, blake2b_512, blake3, sha3_224, sha3_256, sha3_384, sha3_512, ed2k, size, mtime from file_hashes" +mkdir -p "$AUDITDIR/r12/u/x" +chmod 000 "$AUDITDIR/r12/u/u" +# the second row lists the same values for the same file, so is a duplicate as in a hashdeep file +check "every spelling of an unreadable file in a sqlite audit is reported test" \ + "cd '$AUDITDIR/r12/u' && '$HASHIT' -v -a ../u.db . 2>/dev/null > ../u.out; [ \"\$(grep -c 'File could not be read' ../u.out)\" == 1 ] && ! grep -q 'not found' ../u.out" +chmod 644 "$AUDITDIR/r12/u/u" + +# round 13 +for GONE in rm chmod; do + mkdir -p "$AUDITDIR/r13/$GONE/t/sub/deep" + echo a > "$AUDITDIR/r13/$GONE/t/a" && echo c > "$AUDITDIR/r13/$GONE/t/sub/deep/c" + (cd "$AUDITDIR/r13/$GONE/t/sub/deep" && "$HASHIT" -f hashdeep -o ../../../m.hd ../.. > /dev/null && "$HASHIT" -f sqlite -o ../../../m.db ../.. > /dev/null) + if [ $GONE == rm ]; then rm -r "$AUDITDIR/r13/$GONE/t/sub/deep"; else chmod 000 "$AUDITDIR/r13/$GONE/t/sub/deep"; fi + for AUDITFILE in m.hd m.db; do + check "directory an audit file was created in is $GONE'd $AUDITFILE test" \ + "cd '$AUDITDIR/r13/$GONE/t' && '$HASHIT' -a ../$AUDITFILE . 2>/dev/null | grep -q 'Files moved: 0' && '$HASHIT' -a ../$AUDITFILE . 2>/dev/null | grep -q 'Files missing: 1'" + done + chmod 755 "$AUDITDIR/r13/$GONE/t/sub/deep" 2>/dev/null +done +mkdir -p "$AUDITDIR/r13/sl/r/d" "$AUDITDIR/r13/sl/r/ext/e2" +printf e > "$AUDITDIR/r13/sl/r/ext/e2/e" +ln -s ../ext/e2 "$AUDITDIR/r13/sl/r/d/lx" +ln -s r "$AUDITDIR/r13/sl/L" +(cd "$AUDITDIR/r13/sl/L" && hashdeep -l -r d/lx/.. > ../m.hd) +check "symlink and .. from a symlinked working directory matches hashdeep test" "cd '$AUDITDIR/r13/sl/L' && '$HASHIT' -a ../m.hd d/lx/.. | grep -q 'Audit passed'" +mkdir -p "$AUDITDIR/r13/sy/real/data" "$AUDITDIR/r13/sy/real/y" +printf Y > "$AUDITDIR/r13/sy/real/y/f" +ln -s real/data "$AUDITDIR/r13/sy/L" +ln -s real/y "$AUDITDIR/r13/sy/y" +(cd "$AUDITDIR/r13/sy" && hashdeep -l -r L/../y > m.hd) +check "symlink after .. which cleaning also reaches matches hashdeep test" "cd '$AUDITDIR/r13/sy' && '$HASHIT' -a m.hd L/../y | grep -q 'Audit passed'" +mkdir -p "$AUDITDIR/r13/s1/real" +echo X > "$AUDITDIR/r13/s1/real/a" && echo W > "$AUDITDIR/r13/s1/real/b" +ln -s real "$AUDITDIR/r13/s1/L" +(cd "$AUDITDIR/r13/s1" && { md5sum real/b | sed 's/ real\/b$/ a/'; md5sum "$PWD/L/a"; } > real/s.md5) +check "conflicting sum lines through a symlinked sum file directory test" "cd '$AUDITDIR/r13/s1' && ! '$HASHIT' --allow-moved -a L/s.md5 L > /dev/null 2>&1" +mkdir -p "$AUDITDIR/r13/s2/s" +echo X > "$AUDITDIR/r13/s2/s/a" && echo Y > "$AUDITDIR/r13/s2/s/c" +(cd "$AUDITDIR/r13/s2" && { md5sum s/c | sed 's/ s\/c$/ a/'; md5sum s/a; } > s/s.md5) +check "conflicting sum lines meeting through different directories test" "cd '$AUDITDIR/r13/s2' && ! '$HASHIT' --allow-moved -a s/s.md5 s > /dev/null 2>&1" +mkdir -p "$AUDITDIR/r13/s3/s" "$AUDITDIR/r13/s3/x" +echo X > "$AUDITDIR/r13/s3/s/x" +(cd "$AUDITDIR/r13/s3" && { md5sum s/x | sed 's/ s\/x$/ x/'; md5sum s/x | sed "s# s/x\$# $PWD/x#"; } > s/s.md5) +check "sum line naming a directory is not a file test" "cd '$AUDITDIR/r13/s3' && ! '$HASHIT' -a s/s.md5 s > /dev/null 2>&1" +mkdir -p "$AUDITDIR/r13/uv/A" "$AUDITDIR/r13/uv/C" +echo f > "$AUDITDIR/r13/uv/A/f" && echo g > "$AUDITDIR/r13/uv/A/g" && echo cf > "$AUDITDIR/r13/uv/C/f" +(cd "$AUDITDIR/r13/uv/A" && "$HASHIT" -f sqlite -o ../m.db . > /dev/null) +sqlite3 "$AUDITDIR/r13/uv/m.db" "insert into file_hashes select '$AUDITDIR/r13/uv/C/f', crc32, xxhash64, md4, md5, sha1, sha224, sha256, sha384, sha512, blake2b_256, blake2b_512, blake3, sha3_224, sha3_256, sha3_384, sha3_512, ed2k, size, mtime from file_hashes where filepath = './f'" +rm "$AUDITDIR/r13/uv/A/f" && chmod 000 "$AUDITDIR/r13/uv/C/f" +check "missing record sharing a path with an unreadable file is not unreadable test" \ + "cd '$AUDITDIR/r13/uv/C' && '$HASHIT' -v -a ../m.db . 2>/dev/null | grep -q '^./f: File expected but not found'" +chmod 644 "$AUDITDIR/r13/uv/C/f" + +# round 14 +mkdir -p "$AUDITDIR/r14/i1/real" +echo X > "$AUDITDIR/r14/i1/real/a" && ln -s real/a "$AUDITDIR/r14/i1/a" +(cd "$AUDITDIR/r14/i1" && md5sum real/a > real/s.md5 && md5sum a >> real/s.md5) +check "sum lines naming a file and a symlink to it are both checked test" "cd '$AUDITDIR/r14/i1' && '$HASHIT' -a real/s.md5 . | grep -q 'Audit passed'" +mkdir -p "$AUDITDIR/r14/p2/s" +echo X > "$AUDITDIR/r14/p2/x" && ln -s x "$AUDITDIR/r14/p2/a" && echo Y > "$AUDITDIR/r14/p2/s/a" +(cd "$AUDITDIR/r14/p2" && H=$(md5sum s/a | cut -c1-32) && printf '%s a\n%s %s\n%s %s\n' $H $H "$PWD/x" $H "$PWD/a" > s/s.md5) +check "absolute sum lines are not checked through another file test" "cd '$AUDITDIR/r14/p2' && ! '$HASHIT' --allow-moved -a s/s.md5 s > /dev/null 2>&1 && ! md5sum -c s/s.md5 > /dev/null 2>&1" +mkdir -p "$AUDITDIR/r14/p1/s" +echo X > "$AUDITDIR/r14/p1/a" && echo Y > "$AUDITDIR/r14/p1/s/a" +(cd "$AUDITDIR/r14/p1" && H=$(md5sum s/a | cut -c1-32) && printf '%s a\n%s %s\n' $H $H "$PWD/a" > s/s.md5) +check "absolute sum line naming the same path as a relative one is checked test" "cd '$AUDITDIR/r14/p1' && ! '$HASHIT' --allow-moved -a s/s.md5 s > /dev/null 2>&1" +mkdir -p "$AUDITDIR/r14/g1/real" +ln -s real "$AUDITDIR/r14/g1/L" && echo X > "$AUDITDIR/r14/g1/real/a" +(cd "$AUDITDIR/r14/g1/L" && md5sum a > s.md5 && md5sum ../real/a >> s.md5) +check "sum lines naming a file through a symlinked directory and its real path test" \ + "cd '$AUDITDIR/r14/g1/L' && '$HASHIT' -a s.md5 . ../real | grep -q 'Audit passed' && '$HASHIT' -a s.md5 . | grep -q 'Audit passed'" +mkdir -p "$AUDITDIR/r14/lk/r/t/P" "$AUDITDIR/r14/lk/r/other/x" "$AUDITDIR/r14/lk/m" +echo y > "$AUDITDIR/r14/lk/r/y" && cp "$AUDITDIR/r14/lk/r/y" "$AUDITDIR/r14/lk/r/t/y" +ln -s "$AUDITDIR/r14/lk/r/other/x" "$AUDITDIR/r14/lk/r/t/P/lnk" +(cd "$AUDITDIR/r14/lk/r/t/P/lnk" && "$HASHIT" -f hashdeep -o "$AUDITDIR/r14/lk/m/M.hd" ../../y > /dev/null && "$HASHIT" -f sqlite -o "$AUDITDIR/r14/lk/m/M.db" ../../y > /dev/null) +echo MODIFIED > "$AUDITDIR/r14/lk/r/y" +chmod 000 "$AUDITDIR/r14/lk/r/t/P" +for AUDITFILE in M.hd M.db; do + check "symlink in a directory which cannot be searched is not cleaned as text $AUDITFILE test" "cd '$AUDITDIR/r14/lk/r/t' && ! '$HASHIT' -a ../../m/$AUDITFILE y > /dev/null 2>&1" +done +chmod 755 "$AUDITDIR/r14/lk/r/t/P" +mkdir -p "$AUDITDIR/r14/lg/r/t/sub/deep" +ln -s r "$AUDITDIR/r14/lg/L" && ln -s sub/deep "$AUDITDIR/r14/lg/r/t/lnk" && echo a > "$AUDITDIR/r14/lg/r/t/a" +(cd "$AUDITDIR/r14/lg/L/t" && "$HASHIT" -f hashdeep -o ../../m.hd . > /dev/null) +check "symlink and .. leading to the symlinked working directory test" "cd '$AUDITDIR/r14/lg/L/t' && '$HASHIT' -a ../../m.hd lnk/../.. | grep -q 'Audit passed'" +mkdir -p "$AUDITDIR/r14/ud/A" "$AUDITDIR/r14/ud/O" +echo one > "$AUDITDIR/r14/ud/A/f" && echo two > "$AUDITDIR/r14/ud/A/g" +(cd "$AUDITDIR/r14/ud/A" && "$HASHIT" -f sqlite -o ../O/m.db . > /dev/null) +sqlite3 "$AUDITDIR/r14/ud/O/m.db" "insert into file_hashes select './/f', crc32, xxhash64, md4, md5, sha1, sha224, sha256, sha384, sha512, blake2b_256, blake2b_512, blake3, sha3_224, sha3_256, sha3_384, sha3_512, ed2k, size, mtime from file_hashes where filepath = './f'" +mv "$AUDITDIR/r14/ud/A" "$AUDITDIR/r14/ud/B" && mv "$AUDITDIR/r14/ud/O/m.db" "$AUDITDIR/r14/ud/B/" +chmod 000 "$AUDITDIR/r14/ud/B/f" +check "every spelling of an unreadable file in a moved sqlite tree is reported test" \ + "cd '$AUDITDIR/r14/ud/B' && '$HASHIT' -v -a m.db . 2>/dev/null > ../ud.out; [ \"\$(grep -c 'File could not be read' ../ud.out)\" == 1 ] && ! grep -q 'not found' ../ud.out" +chmod 644 "$AUDITDIR/r14/ud/B/f" + +# round 15 +mkdir -p "$AUDITDIR/r15/mh/s" +echo X > "$AUDITDIR/r15/mh/s/a" && ln -s s/a "$AUDITDIR/r15/mh/a" +(cd "$AUDITDIR/r15/mh" && printf 'MD5 (%s/s/a) = %s\nSHA1 (a) = %s\n' "$(pwd)" "$(md5sum s/a | cut -c1-32)" 0000000000000000000000000000000000000000 > s/s.sum) +check "sum lines naming the same file with different hashes are all checked test" \ + "cd '$AUDITDIR/r15/mh' && ! '$HASHIT' -a s/s.sum s > /dev/null 2>&1 && ! '$HASHIT' --allow-moved -a s/s.sum s > /dev/null 2>&1 && ! cksum -c s/s.sum > /dev/null 2>&1" +mkdir -p "$AUDITDIR/r15/mk/s" +echo X > "$AUDITDIR/r15/mk/s/a" && ln -s s/a "$AUDITDIR/r15/mk/a" +(cd "$AUDITDIR/r15/mk" && printf 'MD5 (%s/s/a) = %s\nSHA1 (a) = %s\n' "$(pwd)" "$(md5sum s/a | cut -c1-32)" "$(sha1sum s/a | cut -c1-40)" > s/ok.sum) +check "sum lines naming the same file with different correct hashes pass test" "cd '$AUDITDIR/r15/mk' && '$HASHIT' -a s/ok.sum s | grep -q 'Audit passed' && cksum -c s/ok.sum > /dev/null" +mkdir -p "$AUDITDIR/r15/uo/A" +echo one > "$AUDITDIR/r15/uo/A/f" && echo two > "$AUDITDIR/r15/uo/A/g" +(cd "$AUDITDIR/r15/uo/A" && "$HASHIT" -f sqlite -o ../m.db . > /dev/null) +sqlite3 "$AUDITDIR/r15/uo/m.db" "insert into file_hashes select './/f', crc32, xxhash64, md4, md5, sha1, sha224, sha256, sha384, sha512, blake2b_256, blake2b_512, blake3, sha3_224, sha3_256, sha3_384, sha3_512, ed2k, size, mtime from file_hashes where filepath = './f'" +mv "$AUDITDIR/r15/uo/A" "$AUDITDIR/r15/uo/B" && chmod 000 "$AUDITDIR/r15/uo/B/f" +check "every spelling of an unreadable file in a moved tree with the sqlite file outside it test" \ + "cd '$AUDITDIR/r15/uo/B' && '$HASHIT' -v -a ../m.db . 2>/dev/null > ../uo.out; [ \"\$(grep -c 'File could not be read' ../uo.out)\" == 1 ] && ! grep -q 'not found' ../uo.out" +chmod 644 "$AUDITDIR/r15/uo/B/f" +mkdir -p "$AUDITDIR/r15/lp/p/sub/d" "$AUDITDIR/r15/lp/q" "$AUDITDIR/r15/lp/mx/my" +ln -s "$AUDITDIR/r15/lp/p" "$AUDITDIR/r15/lp/A" && ln -s "$AUDITDIR/r15/lp/q" "$AUDITDIR/r15/lp/p/B" && echo y > "$AUDITDIR/r15/lp/p/sub/y" +printf '%s ../p/sub/d/../y\n' "$(md5sum < "$AUDITDIR/r15/lp/p/sub/y" | cut -c1-32)" > "$AUDITDIR/r15/lp/mx/my/M.md5" +check "same path through a symlinked working directory's ancestor and .. test" "cd '$AUDITDIR/r15/lp/A/B' && '$HASHIT' -a '$AUDITDIR/r15/lp/mx/my/M.md5' ../p/sub/d/.. | grep -q 'Audit passed'" +mkdir -p "$AUDITDIR/r15/ap/R/c" "$AUDITDIR/r15/ap/R/x/e2" "$AUDITDIR/r15/ap/R/d" +printf e > "$AUDITDIR/r15/ap/R/x/e2/e" && ln -s ../x/e2 "$AUDITDIR/r15/ap/R/d/lx" && ln -s R "$AUDITDIR/r15/ap/S" +(cd "$AUDITDIR/r15/ap/R/c" && hashdeep -l -r ../d/lx/.. > ../../m.hd) +check "absolute physical path from a symlinked working directory test" \ + "cd '$AUDITDIR/r15/ap/R/c' && '$HASHIT' -a ../../m.hd '$AUDITDIR/r15/ap/R/x' | grep -q 'Audit passed' && cd '$AUDITDIR/r15/ap/S/c' && '$HASHIT' -a ../../m.hd '$AUDITDIR/r15/ap/R/x' | grep -q 'Audit passed'" +mkdir -p "$AUDITDIR/r15/am/real" +echo a > "$AUDITDIR/r15/am/real/a" && ln -s real "$AUDITDIR/r15/am/L" +(cd "$AUDITDIR/r15/am/real" && "$HASHIT" -f hashdeep --absolute . > ../abs.hd) +check "absolute physical manifest audited from a symlinked working directory test" "cd '$AUDITDIR/r15/am/L' && '$HASHIT' -a ../abs.hd . | grep -q 'Audit passed'" +mkdir -p "$AUDITDIR/r15/sd/r/t/sub" +echo a > "$AUDITDIR/r15/sd/r/t/a" && echo b > "$AUDITDIR/r15/sd/r/t/sub/b" && ln -s r/t/sub "$AUDITDIR/r15/sd/D" +(cd "$AUDITDIR/r15/sd/r/t" && "$HASHIT" -f sqlite -o ../m.db . > /dev/null && "$HASHIT" -f hashdeep -o ../m.hd . > /dev/null) +for AUDITFILE in m.db m.hd; do + check "audit with .. from a working directory which is a symlink into the tree $AUDITFILE test" "cd '$AUDITDIR/r15/sd/D' && '$HASHIT' -a '$AUDITDIR/r15/sd/r/$AUDITFILE' .. | grep -q 'Audit passed'" +done +mkdir -p "$AUDITDIR/r15/sl/r/t/sub" "$AUDITDIR/r15/sl/r/m" +ln -s "$AUDITDIR/r15/sl/r" "$AUDITDIR/r15/sl/L" && echo a > "$AUDITDIR/r15/sl/r/t/a" && echo b > "$AUDITDIR/r15/sl/r/t/sub/b" +(cd "$AUDITDIR/r15/sl/L/t/sub" && "$HASHIT" -f sqlite -o "$AUDITDIR/r15/sl/L/m/M.db" .. > /dev/null) +check "sqlite made with .. from a symlinked working directory audits from there test" \ + "cd '$AUDITDIR/r15/sl/L/t/sub' && '$HASHIT' -a '$AUDITDIR/r15/sl/L/m/M.db' .. | grep -q 'Audit passed' && cd .. && '$HASHIT' -a '$AUDITDIR/r15/sl/L/m/M.db' . | grep -q 'Audit passed'" + +# round 16 +mkdir -p "$AUDITDIR/r16/c1" "$AUDITDIR/r16/c3/s" +echo A > "$AUDITDIR/r16/c1/a" && echo A > "$AUDITDIR/r16/c3/a" +(cd "$AUDITDIR/r16/c1" && H=$(md5sum a | cut -c1-32) && printf '%s ./a\n%s a\n%s a\n' $H $H 00000000000000000000000000000000 > s.md5) +(cd "$AUDITDIR/r16/c3" && H=$(md5sum a | cut -c1-32) && printf '%s %s\n%s a\n%s a\n' $H "$(pwd)/a" $H 00000000000000000000000000000000 > s/s.md5) +check "conflicting sum line after another spelling of the file is checked test" \ + "cd '$AUDITDIR/r16/c1' && ! '$HASHIT' -a s.md5 a > /dev/null 2>&1 && cd '$AUDITDIR/r16/c3' && ! '$HASHIT' -a s/s.md5 a > /dev/null 2>&1 && ! md5sum -c s/s.md5 > /dev/null 2>&1" +mkdir -p "$AUDITDIR/r16/ns/p" "$AUDITDIR/r16/ns/q" "$AUDITDIR/r16/ns/m" +ln -s "$AUDITDIR/r16/ns/p" "$AUDITDIR/r16/ns/A" && ln -s "$AUDITDIR/r16/ns/q" "$AUDITDIR/r16/ns/p/B" && echo f > "$AUDITDIR/r16/ns/q/f" +(cd "$AUDITDIR/r16/ns/A/B" && "$HASHIT" -f sqlite -o "$AUDITDIR/r16/ns/m/M.db" "$AUDITDIR/r16/ns/p/B" > /dev/null && "$HASHIT" -f hashdeep -o "$AUDITDIR/r16/ns/m/M.hd" "$AUDITDIR/r16/ns/p/B" > /dev/null) +for AUDITFILE in M.db M.hd; do + check "nested symlinked working directory ancestors $AUDITFILE test" \ + "cd '$AUDITDIR/r16/ns/A/B' && '$HASHIT' -a '$AUDITDIR/r16/ns/m/$AUDITFILE' '$AUDITDIR/r16/ns/p/B' | grep -q 'Audit passed' && '$HASHIT' -a '$AUDITDIR/r16/ns/m/$AUDITFILE' . | grep -q 'Audit passed' && '$HASHIT' -a '$AUDITDIR/r16/ns/m/$AUDITFILE' '$AUDITDIR/r16/ns/q' | grep -q 'Audit passed'" +done +mkdir -p "$AUDITDIR/r16/nr/p/x/y" "$AUDITDIR/r16/nr/m" +ln -s "$AUDITDIR/r16/nr/p" "$AUDITDIR/r16/nr/A" && ln -s "$AUDITDIR/r16/nr/p/x/y" "$AUDITDIR/r16/nr/p/B" && echo y > "$AUDITDIR/r16/nr/p/x/y/f" +(cd "$AUDITDIR/r16/nr/A/B" && "$HASHIT" -f hashdeep -o "$AUDITDIR/r16/nr/m/M.hd" . > /dev/null) +check "working directory ancestor really inside another's real directory test" \ + "cd '$AUDITDIR/r16/nr/A/B' && '$HASHIT' -a '$AUDITDIR/r16/nr/m/M.hd' ../y | grep -q 'Audit passed' && '$HASHIT' -a '$AUDITDIR/r16/nr/m/M.hd' '$AUDITDIR/r16/nr/A/x/y' | grep -q 'Audit passed'" +mkdir -p "$AUDITDIR/r16/sl/a" +ln -s . "$AUDITDIR/r16/sl/a/b" && echo f > "$AUDITDIR/r16/sl/a/f" +check "working directory through a symlink to itself with // test" \ + "cd '/$AUDITDIR/r16/sl/a/b' && '$HASHIT' -f hashdeep -o ../../m.hd . > /dev/null && '$HASHIT' -a ../../m.hd . | grep -q 'Audit passed'" +mkdir -p "$AUDITDIR/r16/dp/p" "$AUDITDIR/r16/dp/q" +ln -s "$AUDITDIR/r16/dp/p" "$AUDITDIR/r16/dp/A" && ln -s "$AUDITDIR/r16/dp/q" "$AUDITDIR/r16/dp/p/B" && echo f > "$AUDITDIR/r16/dp/q/f" && ln -s gone "$AUDITDIR/r16/dp/q/dl" +printf '%s %s\n' "$(md5sum < "$AUDITDIR/r16/dp/q/f" | cut -c1-32)" "$AUDITDIR/r16/dp/q/dl/../f" > "$AUDITDIR/r16/dp/s.md5" +check "dangling symlink and .. through where the working directory really is never matches test" "cd '$AUDITDIR/r16/dp/A/B' && ! '$HASHIT' -a '$AUDITDIR/r16/dp/s.md5' . > /dev/null 2>&1" +mkdir -p "$AUDITDIR/r16/pl/sub" +echo A > "$AUDITDIR/r16/pl/sub/a" && ln -s . "$AUDITDIR/r16/pl/L" +(cd "$AUDITDIR/r16/pl/L/sub" && printf '%s ../L/sub/a\n' "$(md5sum a | cut -c1-32)" > s.md5) +check "working directory through a symlink to its own parent test" "cd '$AUDITDIR/r16/pl/L/sub' && '$HASHIT' -a s.md5 a | grep -q 'Audit passed' && md5sum -c s.md5 > /dev/null" + +# round 17 +mkdir -p "$AUDITDIR/r17/rt/d" "$AUDITDIR/r17/rt/m" +ln -s / "$AUDITDIR/r17/rt/R" && echo X > "$AUDITDIR/r17/rt/d/f" +P2="$AUDITDIR/r17/rt/R${AUDITDIR#/}/r17/rt/d/f" +mkdir -p "$(dirname "$P2")" && echo X > "$P2" +(cd "$AUDITDIR/r17/rt" && "$HASHIT" -f sqlite -o "$AUDITDIR/r17/rt/m/M.db" "$P2" > /dev/null) +rm "$P2" +check "working directory through a symlink to / does not match another file test" "cd '$AUDITDIR/r17/rt/R' && ! '$HASHIT' -a '$AUDITDIR/r17/rt/m/M.db' '$AUDITDIR/r17/rt/d' > /dev/null 2>&1" +mkdir -p "$AUDITDIR/r17/ro/d" +ln -s / "$AUDITDIR/r17/ro/R" && echo X > "$AUDITDIR/r17/ro/d/f" +(cd "$AUDITDIR/r17/ro/R${AUDITDIR}/r17/ro" && "$HASHIT" -f sqlite -o ../ro.db d > /dev/null && "$HASHIT" -f hashdeep -o ../ro.hd d > /dev/null) +for AUDITFILE in ro.db ro.hd; do + check "working directory through a symlink to / passes $AUDITFILE test" "cd '$AUDITDIR/r17/ro/R${AUDITDIR}/r17/ro' && '$HASHIT' -a ../$AUDITFILE d | grep -q 'Audit passed' && '$HASHIT' -a ../$AUDITFILE '$AUDITDIR/r17/ro/d' | grep -q 'Audit passed'" +done +mkdir -p "$AUDITDIR/r17/af/x" "$AUDITDIR/r17/af/y/sub" +printf A > "$AUDITDIR/r17/af/x/a" && printf A > "$AUDITDIR/r17/af/y/a" && ln -s ../y/sub "$AUDITDIR/r17/af/x/lnk" +(cd "$AUDITDIR/r17/af/y" && "$HASHIT" -f hashdeep -o m.hd a > /dev/null && "$HASHIT" -f sqlite -o m.db a > /dev/null && sha256sum a > m.sha256) +rm "$AUDITDIR/r17/af/y/a" +for AUDITFILE in m.hd m.db m.sha256; do + check "audit file given through a symlink and .. is in the directory the OS opens $AUDITFILE test" "cd '$AUDITDIR/r17/af' && ! '$HASHIT' -a x/lnk/../$AUDITFILE x/a > /dev/null 2>&1" +done + +# a database made from overlapping paths lists a file twice, and the second row is never looked up +mkdir -p "$AUDITDIR/r18/t/sub" +echo a > "$AUDITDIR/r18/t/a" +echo b > "$AUDITDIR/r18/t/sub/b" +(cd "$AUDITDIR/r18/t" && "$HASHIT" -r -f sqlite -o ../ov.db . sub > /dev/null && "$HASHIT" -f sqlite -o ../same.db a ./a "$AUDITDIR/r18/t/a" > /dev/null) +check "sqlite rows for the same file from overlapping paths pass test" "cd '$AUDITDIR/r18/t' && '$HASHIT' -r -a ../ov.db . | grep -q 'Audit passed'" +check "sqlite rows for the same file by different spellings pass test" "cd '$AUDITDIR/r18/t' && '$HASHIT' -a ../same.db a | grep -q 'Audit passed'" +cp "$AUDITDIR/r18/ov.db" "$AUDITDIR/r18/conflict.db" +sqlite3 "$AUDITDIR/r18/conflict.db" "update file_hashes set md5 = '00000000000000000000000000000000' where filepath = 'sub/b'" +check "sqlite rows for the same file with other values fail test" "cd '$AUDITDIR/r18/t' && ! '$HASHIT' -r -a ../conflict.db . > /dev/null 2>&1" +echo z > "$AUDITDIR/r18/t/sub/b" +check "sqlite rows for the same file from overlapping paths catch a modified file test" "cd '$AUDITDIR/r18/t' && ! '$HASHIT' -r -a ../ov.db . > /dev/null 2>&1" +rm "$AUDITDIR/r18/t/sub/b" +check "sqlite rows for the same file from overlapping paths catch a deleted file test" "cd '$AUDITDIR/r18/t' && ! '$HASHIT' -r -a ../ov.db . > /dev/null 2>&1" + +# a file moved to where the audit file's directory places its record is still moved, as an audit +# is only matched through one directory +for AUDITFILE in m.hd m.db m.sha256; do + mkdir -p "$AUDITDIR/r18/mix/$AUDITFILE/q/d" + echo hello > "$AUDITDIR/r18/mix/$AUDITFILE/q/d/a" && echo bb > "$AUDITDIR/r18/mix/$AUDITFILE/q/d/b" + case $AUDITFILE in + m.hd) (cd "$AUDITDIR/r18/mix/$AUDITFILE/q" && "$HASHIT" -f hashdeep -o ../m.hd d > /dev/null) ;; + m.db) (cd "$AUDITDIR/r18/mix/$AUDITFILE/q" && "$HASHIT" -f sqlite -o ../m.db d > /dev/null) ;; + m.sha256) (cd "$AUDITDIR/r18/mix/$AUDITFILE/q" && sha256sum d/a d/b > ../m.sha256) ;; + esac + mv "$AUDITDIR/r18/mix/$AUDITFILE/$AUDITFILE" "$AUDITDIR/r18/mix/$AUDITFILE/q/d/" + check "audit file inside the tree passes before a move $AUDITFILE test" "cd '$AUDITDIR/r18/mix/$AUDITFILE/q' && '$HASHIT' -a d/$AUDITFILE d | grep -q 'Audit passed'" + mkdir "$AUDITDIR/r18/mix/$AUDITFILE/q/d/d" && mv "$AUDITDIR/r18/mix/$AUDITFILE/q/d/a" "$AUDITDIR/r18/mix/$AUDITFILE/q/d/d/a" + check "file moved to where the audit file's directory places it is moved $AUDITFILE test" "cd '$AUDITDIR/r18/mix/$AUDITFILE/q' && '$HASHIT' -v -a d/$AUDITFILE d | grep -q 'File moved'" + check "file moved to where the audit file's directory places it passes with allow moved $AUDITFILE test" "cd '$AUDITDIR/r18/mix/$AUDITFILE/q' && '$HASHIT' --allow-moved -a d/$AUDITFILE d | grep -q 'Audit passed'" +done + +# round 19 +# a sum line is only a duplicate of another when it names the checked file through the directory +# the audit is matched through +mkdir -p "$AUDITDIR/r19/gk/r/a/a" +touch "$AUDITDIR/r19/gk/r/.gitkeep" "$AUDITDIR/r19/gk/r/a/.gitkeep" "$AUDITDIR/r19/gk/r/a/a/.gitkeep" +(cd "$AUDITDIR/r19/gk/r" && md5sum .gitkeep a/.gitkeep a/a/.gitkeep > S.md5) +rm "$AUDITDIR/r19/gk/r/.gitkeep" +check "deleted file with an identical file of the same name below it is missing test" "cd '$AUDITDIR/r19/gk/r/a' && ! '$HASHIT' -a ../S.md5 .. > /dev/null 2>&1" +mkdir -p "$AUDITDIR/r19/ap/t" +echo a > "$AUDITDIR/r19/ap/t/a" && echo b > "$AUDITDIR/r19/ap/t/b" +(cd "$AUDITDIR/r19/ap/t" && md5sum a b > s.md5) +(cd "$AUDITDIR/r19/ap" && md5sum t/a >> t/s.md5) +mv "$AUDITDIR/r19/ap/t/b" "$AUDITDIR/r19/ap/b" +check "sum line through another directory does not hide a moved file test" "cd '$AUDITDIR/r19/ap' && ! '$HASHIT' -a t/s.md5 . > /dev/null 2>&1" +# a record dropped as a duplicate names another file once the tree is copied elsewhere +for AUDITFILE in x.hd x.db; do + mkdir -p "$AUDITDIR/r19/cp/$AUDITFILE/w" "$AUDITDIR/r19/cp/$AUDITFILE/m" + echo A > "$AUDITDIR/r19/cp/$AUDITFILE/w/a" && echo B > "$AUDITDIR/r19/cp/$AUDITFILE/w/b" + FORMAT=hashdeep; [ $AUDITFILE = x.db ] && FORMAT=sqlite + (cd "$AUDITDIR/r19/cp/$AUDITFILE/w" && "$HASHIT" -r -f $FORMAT -o ../m/$AUDITFILE . "$AUDITDIR/r19/cp/$AUDITFILE/w/a" > /dev/null) + check "duplicate absolute record in place passes $AUDITFILE test" "cd '$AUDITDIR/r19/cp/$AUDITFILE/w' && '$HASHIT' -a ../m/$AUDITFILE . | grep -q 'Audit passed'" + cp -r "$AUDITDIR/r19/cp/$AUDITFILE/w" "$AUDITDIR/r19/cp/$AUDITFILE/z" && cp "$AUDITDIR/r19/cp/$AUDITFILE/m/$AUDITFILE" "$AUDITDIR/r19/cp/$AUDITFILE/z/" + rm -rf "$AUDITDIR/r19/cp/$AUDITFILE/w" + check "duplicate absolute record into a tree copied elsewhere is missing $AUDITFILE test" "cd '$AUDITDIR/r19/cp/$AUDITFILE/z' && ! '$HASHIT' -a $AUDITFILE . > /dev/null 2>&1" +done +# a database whose rows are not keyed by path as hashit writes them is refused, as a path listed +# twice would only be audited once, and a rowid column hides the real one +mkdir -p "$AUDITDIR/r19/pk/t" +printf A > "$AUDITDIR/r19/pk/t/a" +(cd "$AUDITDIR/r19/pk/t" && "$HASHIT" -f sqlite -o ../m.db . > /dev/null) +cp "$AUDITDIR/r19/pk/m.db" "$AUDITDIR/r19/pk/r.db" +sqlite3 "$AUDITDIR/r19/pk/m.db" "create table f2 as select * from file_hashes; drop table file_hashes; alter table f2 rename to file_hashes; +insert into file_hashes select * from file_hashes;" +check "sqlite database without filepath as primary key is refused test" "cd '$AUDITDIR/r19/pk/t' && '$HASHIT' -a ../m.db . > /dev/null 2>&1; [ \$? -eq 2 ]" +sqlite3 "$AUDITDIR/r19/pk/r.db" "alter table file_hashes add column rowid integer;" +check "sqlite database with a rowid column is refused test" "cd '$AUDITDIR/r19/pk/t' && '$HASHIT' -a ../r.db . 2>&1 | grep -q 'was not created by hashit'" +(cd "$AUDITDIR/r19/pk/t" && "$HASHIT" -f sqlite -o ../g.db --overwrite . > /dev/null && "$HASHIT" -f sqlite -o ../n.db . > /dev/null) +SCHEMA=$(sqlite3 "$AUDITDIR/r19/pk/g.db" "select sql from sqlite_master where name = 'file_hashes'") +sqlite3 "$AUDITDIR/r19/pk/g.db" "alter table file_hashes rename to old; $(echo "$SCHEMA" | sed 's/mtime text null/mtime text null, rowid integer generated always as (1) virtual/'); insert into file_hashes select * from old; drop table old;" +check "sqlite database with a generated rowid column is refused test" "cd '$AUDITDIR/r19/pk/t' && '$HASHIT' -a ../g.db . 2>&1 | grep -q 'was not created by hashit'" +sqlite3 "$AUDITDIR/r19/pk/n.db" "alter table file_hashes rename to old; $(echo "$SCHEMA" | sed 's/filepath text primary key/filepath text primary key collate nocase/'); insert into file_hashes select * from old; drop table old;" +check "sqlite database comparing paths without case is refused test" "cd '$AUDITDIR/r19/pk/t' && '$HASHIT' -a ../n.db . 2>&1 | grep -q 'was not created by hashit'" +(cd "$AUDITDIR/r19/pk/t" && "$HASHIT" -f sqlite -o ../c.db . > /dev/null && "$HASHIT" -f sqlite -o ../i.db . > /dev/null && "$HASHIT" -f sqlite -o ../z.db . > /dev/null) +sqlite3 "$AUDITDIR/r19/pk/c.db" "alter table file_hashes rename to old; $(echo "$SCHEMA" | sed 's/filepath text primary key/filepath text collate nocase/; s/mtime text null/mtime text null, primary key (filepath collate binary)/'); insert into file_hashes select * from old; drop table old;" +check "sqlite database comparing the path column without case is refused test" "cd '$AUDITDIR/r19/pk/t' && '$HASHIT' -a ../c.db . 2>&1 | grep -q 'was not created by hashit'" +sqlite3 "$AUDITDIR/r19/pk/i.db" "alter table file_hashes rename to old; $(echo "$SCHEMA" | sed 's/filepath text primary key/filepath int primary key/'); insert into file_hashes select * from old; drop table old;" +check "sqlite database with numeric paths is refused test" "cd '$AUDITDIR/r19/pk/t' && '$HASHIT' -a ../i.db . 2>&1 | grep -q 'was not created by hashit'" +sqlite3 "$AUDITDIR/r19/pk/z.db" "insert into file_hashes (filepath, md5, size) values (null, 'x', 1);" +check "sqlite database with a row without a path is refused test" "cd '$AUDITDIR/r19/pk/t' && '$HASHIT' -a ../z.db . 2>&1 | grep -q 'was not created by hashit'" +# a relative row is only the same path as an absolute one through the directory hashit was invoked from +mkdir -p "$AUDITDIR/r21/D" "$AUDITDIR/r21/T" "$AUDITDIR/r21/M" +printf A > "$AUDITDIR/r21/D/a" && printf A > "$AUDITDIR/r21/T/a" +(cd "$AUDITDIR/r21/D" && "$HASHIT" -f sqlite -o ../M/m.db a "$AUDITDIR/r21/T/a" > /dev/null) +rm "$AUDITDIR/r21/D/a" +check "sqlite relative row is not a duplicate of an absolute row through the working directory test" "cd '$AUDITDIR/r21/T' && ! '$HASHIT' -a ../M/m.db . > /dev/null 2>&1" +# a sum file listing every file by relative and absolute path passes in place from another directory +mkdir -p "$AUDITDIR/r20/t/s" +echo a > "$AUDITDIR/r20/t/a" && echo b > "$AUDITDIR/r20/t/s/b" +(cd "$AUDITDIR/r20/t" && md5sum a s/b "$AUDITDIR/r20/t/a" "$AUDITDIR/r20/t/s/b" > s.md5) +check "sum file listing files by relative and absolute path passes from parent test" "cd '$AUDITDIR/r20' && '$HASHIT' -a t/s.md5 t | grep -q 'Audit passed'" +cp "$AUDITDIR/r20/t/a" "$AUDITDIR/r20/t/extra" +check "sum file listing files by relative and absolute path fails with a copy allowing moves test" "cd '$AUDITDIR/r20' && ! '$HASHIT' --allow-moved -a t/s.md5 t > /dev/null 2>&1" +rm "$AUDITDIR/r20/t/extra" "$AUDITDIR/r20/t/s/b" +check "sum file listing files by relative and absolute path fails when one is deleted test" "cd '$AUDITDIR/r20' && ! '$HASHIT' -a t/s.md5 t > /dev/null 2>&1" +# the directory most files match through is used, so the file which moved is the one reported +mkdir -p "$AUDITDIR/r19/maj/t" +for F in a b c d e; do echo $F > "$AUDITDIR/r19/maj/t/$F"; done +(cd "$AUDITDIR/r19/maj/t" && md5sum a b c d e > s.md5) +mv "$AUDITDIR/r19/maj/t/a" "$AUDITDIR/r19/maj/a" +check "file moved to where the working directory places it is the one reported test" "cd '$AUDITDIR/r19/maj' && '$HASHIT' -v -a t/s.md5 . | grep -q 'a -> ./a: File moved'" + +# --allow-new passes an audit with files not in the audit file, but fails for anything else +for AUDITFILE in m.hd m.db m.md5; do + mkdir -p "$AUDITDIR/an/$AUDITFILE/t" + echo a > "$AUDITDIR/an/$AUDITFILE/t/a" && echo b > "$AUDITDIR/an/$AUDITFILE/t/b" + case $AUDITFILE in + m.hd) (cd "$AUDITDIR/an/$AUDITFILE/t" && "$HASHIT" -f hashdeep -o ../m.hd . > /dev/null) ;; + m.db) (cd "$AUDITDIR/an/$AUDITFILE/t" && "$HASHIT" -f sqlite -o ../m.db . > /dev/null) ;; + m.md5) (cd "$AUDITDIR/an/$AUDITFILE/t" && md5sum a b > ../m.md5) ;; + esac + echo new > "$AUDITDIR/an/$AUDITFILE/t/new" + check "new file fails an audit $AUDITFILE test" "cd '$AUDITDIR/an/$AUDITFILE/t' && ! '$HASHIT' -a ../$AUDITFILE . > /dev/null 2>&1" + check "new file passes with allow new $AUDITFILE test" "cd '$AUDITDIR/an/$AUDITFILE/t' && '$HASHIT' --allow-new -v -a ../$AUDITFILE . > ../out && grep -q 'Audit passed' ../out && grep -q 'new: File new' ../out" + cp "$AUDITDIR/an/$AUDITFILE/t/a" "$AUDITDIR/an/$AUDITFILE/t/copy" + check "copy of a known file passes with allow new $AUDITFILE test" "cd '$AUDITDIR/an/$AUDITFILE/t' && '$HASHIT' --allow-new -a ../$AUDITFILE . | grep -q 'Audit passed'" + mv "$AUDITDIR/an/$AUDITFILE/t/b" "$AUDITDIR/an/$AUDITFILE/t/moved" + check "moved file fails with allow new $AUDITFILE test" "cd '$AUDITDIR/an/$AUDITFILE/t' && ! '$HASHIT' --allow-new -a ../$AUDITFILE . > /dev/null 2>&1" + check "moved file passes with allow new and allow moved $AUDITFILE test" "cd '$AUDITDIR/an/$AUDITFILE/t' && '$HASHIT' --allow-new --allow-moved -a ../$AUDITFILE . | grep -q 'Audit passed'" + echo changed > "$AUDITDIR/an/$AUDITFILE/t/a" + check "modified file fails with allow new $AUDITFILE test" "cd '$AUDITDIR/an/$AUDITFILE/t' && ! '$HASHIT' --allow-new --allow-moved -a ../$AUDITFILE . > /dev/null 2>&1" + rm "$AUDITDIR/an/$AUDITFILE/t/a" "$AUDITDIR/an/$AUDITFILE/t/copy" + check "missing file fails with allow new $AUDITFILE test" "cd '$AUDITDIR/an/$AUDITFILE/t' && ! '$HASHIT' --allow-new --allow-moved -a ../$AUDITFILE . > /dev/null 2>&1" +done +check "allow new outside an audit warns test" "'$HASHIT' --allow-new '$AUDITDIR/an/m.md5/t' 2>&1 >/dev/null | grep -q 'allow-new only applies'" + # a manifest kept with the files can be audited after they are copied elsewhere mkdir -p "$AUDITDIR/ship/orig/tree/sub" "$AUDITDIR/ship/copy" echo 1 > "$AUDITDIR/ship/orig/tree/one"