#!/usr/bin/env python3
"""Insert allow rules for new deny-log entries into the pe-proxy policy file.

Reads rootstrap-check-deny log files, converts each unique (subject, target)
pair to an allow policy line and inserts it before the first policy line that
would otherwise block it. Matching follows proxy/proxy.c (pat_init/pat_match).

The tool is strict: an allow is only added when it is safe to do so. Whatever
cannot be added is reported (NOT ADDED, SKIPPED, UNPARSED) and counted in the
summary, existing rules are never changed, and the result is verified before
anything is written. See README in this directory for all rules.

Usage:
  proxy-deny2policy LOG [LOG...] -p POLICY [--dry-run]
"""

import argparse
import collections
import re
import sys

TAG = 'rootstrap-check-deny'
LINE_RE = re.compile(
    r'^\[' + TAG + r'\]\s+'
    r'\[PID:\d+\s+TID:\d+\s+EXE:[^\]]*\]:'
    r'(?P<lib>[^:]+):(?P<op>[^:]+):(?P<target>.+):rule=\d+(?:\s+\(permissive\))?\s*$'
)

VERDICTS = ('allow', 'deny', 'log')
PATH_MAX = 4096
# Functions that only make sense on a directory.
DIR_OPS = frozenset(['chdir', 'mkdir', 'mkdirat', 'rmdir', 'opendir', 'scandir',
                     'mkdtemp', 'ftw', 'nftw', 'chroot'])


def lib_pattern(lib):
    dir_ = lib.rsplit('/', 1)[0]
    name = lib.rsplit('/', 1)[-1]
    m = re.match(r'^(?P<base>.+\.so)\.[\d.]+$', name)
    if m:
        name = m.group('base') + '*'
    else:
        m = re.match(r'^(?P<base>.+)-[\d.]+\.so$', name)
        if m:
            name = m.group('base') + '-*'
    return dir_ + '/' + name


def pat_init(s):
    """Same as pat_init() in proxy.c: returns (str, children_only, prefix)."""
    if s.endswith('*'):
        return (s[:-1], False, True)
    stripped = s.rstrip('/')
    children_only = stripped != s and len(stripped) != 0
    return (stripped, children_only, False)


def pat_match(pat, path):
    """Same as pat_match() in proxy.c."""
    string, children_only, prefix = pat
    if not path.startswith(string):
        return False
    if prefix:
        return True
    rest = path[len(string):]
    if rest == '':
        return not children_only
    if rest[0] != '/':
        return False
    if children_only:
        return rest[1:] != ''
    return True


def witness(pat):
    """The shortest path matched by the pattern."""
    string, children_only, _prefix = pat
    return string + '/x' if children_only else string


def overlap(a, b):
    """True if some path is matched by both patterns."""
    return pat_match(a, witness(b)) or pat_match(b, witness(a))


class Rule:
    def __init__(self, idx, lineno, subject, target, verdict):
        self.idx = idx
        self.lineno = lineno
        self.subject = subject
        self.target = target
        self.verdict = verdict
        self.subj_pat = pat_init(subject)
        self.targ_pat = pat_init(target)

    def matches(self, lib, target):
        return pat_match(self.subj_pat, lib) and pat_match(self.targ_pat, target)


def parse_policy(policy_lines, path):
    """Parse like policy_load(): any malformed rule invalidates the policy."""
    rules = []
    for idx, line in enumerate(policy_lines):
        parts = line.split()
        if not parts or parts[0].startswith('#'):
            continue
        if (len(parts) != 3 or parts[2] not in VERDICTS
                or not parts[0].startswith('/') or not parts[1].startswith('/')):
            sys.exit('error: {}:{}: malformed rule, the policy loader would '
                     'discard the whole policy: {!r}'.format(path, idx + 1, line))
        rules.append(Rule(idx, idx + 1, parts[0], parts[1], parts[2]))
    return rules


def first_rule(lib, target, rules):
    """First rule matching both subject and target (what the C code applies)."""
    for r in rules:
        if r.matches(lib, target):
            return r
    return None


def names_access(rule, subj_pat, target):
    """A deny or log rule that names exactly this target for a subject that
    overlaps the subject of the allow we would write."""
    return (rule.verdict in ('deny', 'log') and rule.targ_pat == pat_init(target)
            and overlap(rule.subj_pat, subj_pat))


def rule_problem(subject, target):
    """Why SUBJECT TARGET cannot be written as a policy rule, or None.

    A rule is only safe to write if the policy loader reads it back as exactly
    three fields and the patterns mean what was logged."""
    for name, value in (('subject', subject), ('target', target)):
        if not value.startswith('/'):
            return '{} {!r} is not an absolute path'.format(name, value)
        if '�' in value:
            return '{} {!r} contains bytes that are not valid UTF-8'.format(name, value)
        if re.search(r'\s', value):
            return '{} {!r} contains whitespace'.format(name, value)
        if len(value) > PATH_MAX:
            return '{} is longer than PATH_MAX'.format(name)
    if target.endswith('*'):
        return 'target ends with *, which would turn it into a prefix pattern'
    if target.endswith('/'):
        return ('target ends with /, which would match only what is under it '
                '(and "/" alone would match everything)')
    return None


def dir_problem(target, ops, ancestors):
    """Why the target is certainly a directory, or None.

    A plain path rule also matches everything below the path, so for a
    directory it would allow far more than was logged."""
    if target in ancestors:
        reason = 'other logged paths are below it'
    elif ops & DIR_OPS:
        reason = 'it is accessed with ' + ', '.join(sorted(ops & DIR_OPS))
    else:
        return None
    return ('the target is a directory ({}); a plain path rule would also allow '
            'everything below it. Allowing only the directory itself needs a '
            '"TARGET/ deny" and "TARGET allow" pair'.format(reason))


def fmt(subject, target, verdict):
    return '{} {} {}'.format(subject, target, verdict)


def insertion_point(policy_lines, idx):
    """Move above the comments preceding the blocking rule; blank lines
    between or around them do not stop the search."""
    def skippable(i):
        s = policy_lines[i].strip()
        return s == '' or s.startswith('#')
    start = idx
    while start > 0 and skippable(start - 1):
        start -= 1
    while start < idx and policy_lines[start].strip() == '':
        start += 1  # keep leading blank lines above the inserted rules
    return start


def build_policy(policy_lines, new):
    """The policy with the new allow lines inserted; new: key -> blocking rule."""
    groups = {}
    for (subject, target), blocker in sorted(new.items()):
        groups.setdefault(insertion_point(policy_lines, blocker.idx), []).append(
            fmt(subject, target, 'allow'))
    lines = list(policy_lines)
    # Descending order: inserting at a higher index never shifts a lower one.
    for idx in sorted(groups, reverse=True):
        lines[idx:idx] = groups[idx]
    return lines


def verify(path, rules, new_lines, entries, queued):
    """Check the result before it is written; exit without writing on failure.

    Every access that got a new rule must end up allowed, and no other logged
    access may change its verdict (nothing may be allowed by accident)."""
    after_rules = parse_policy(new_lines, path)
    errors = []
    for lib, target in sorted(entries):
        before = first_rule(lib, target, rules)
        after = first_rule(lib, target, after_rules)
        before_verdict = before.verdict if before else 'allow'
        after_verdict = after.verdict if after else 'allow'
        if (lib, target) in queued:
            if after_verdict != 'allow':
                errors.append('the new rule does not allow {} by {}: still {} by '
                              'policy line {}'.format(target, lib, after_verdict,
                                                      after.lineno))
        elif after_verdict != before_verdict:
            errors.append('{} by {} would change from {} to {} without a rule '
                          'being added for it'.format(target, lib, before_verdict,
                                                      after_verdict))
    if errors:
        for e in errors:
            print('ERROR: verification failed: ' + e, file=sys.stderr)
        sys.exit('error: the policy was NOT modified')


def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument('logs', nargs='+', help='rootstrap-check-deny log file(s)')
    ap.add_argument('-p', '--policy', required=True, help='policy file to update')
    ap.add_argument('--dry-run', action='store_true',
                    help='print the changes that would be made, do not modify the policy')
    args = ap.parse_args()

    with open(args.policy, encoding='utf-8') as fh:
        policy_lines = fh.read().splitlines()
    rules = parse_policy(policy_lines, args.policy)

    entries = {}  # (lib, target) -> set of function names
    unparsed = 0
    for log in args.logs:
        with open(log, encoding='utf-8', errors='replace') as fh:
            for lineno, line in enumerate(fh, 1):
                m = LINE_RE.match(line)
                if m:
                    entries.setdefault((m.group('lib'), m.group('target')),
                                       set()).add(m.group('op'))
                elif TAG in line:
                    unparsed += 1
                    print('UNPARSED: {}:{}: the line looks like a deny log entry but '
                          'cannot be parsed, it is ignored:\n    {}'.format(
                              log, lineno, line.rstrip()[:200]))

    ancestors = set()
    for _lib, target in entries:
        parts = target.split('/')
        for i in range(2, len(parts)):
            ancestors.add('/'.join(parts[:i]))

    outcome = {}  # (lib, target) -> category, for the summary
    new = {}      # (subject_pattern, target) -> blocking rule, lowest line wins
    queued = set()
    reported = set()

    def report_once(key, text):
        if key not in reported:
            reported.add(key)
            print(text)

    for lib, target in sorted(entries):
        access = (lib, target)
        blocker = first_rule(lib, target, rules)
        if blocker is None or blocker.verdict == 'allow':
            outcome[access] = 'already allowed'
            continue
        subject = lib_pattern(lib)
        key = (subject, target)
        allow_line = fmt(subject, target, 'allow')

        problem = rule_problem(subject, target) or dir_problem(
            target, entries[access], ancestors)
        if problem is not None:
            outcome[access] = 'skipped'
            report_once((key, 'skipped'),
                        'SKIPPED: cannot write a rule for the access to {} by {}: {}.\n'
                        '  The following rule was not added, add it by hand if it is '
                        'needed:\n    {}'.format(target, lib, problem, allow_line))
            continue

        exact = next((r for r in rules if names_access(r, pat_init(subject), target)),
                     None)
        if exact is not None:
            outcome[access] = 'exact'
            report_once((key, exact.idx),
                        'NOT ADDED: policy line {} is a {} rule for exactly this '
                        'target and a subject that overlaps the new rule:\n    {}\n'
                        '  The log reports an access to {} by {}, but the existing {} '
                        'rule is kept, so the following rule was not '
                        'added:\n    {}'.format(exact.lineno, exact.verdict,
                                               policy_lines[exact.idx].strip(), target,
                                               lib, exact.verdict, allow_line))
            continue

        shadowed = next((r for r in rules if r.verdict == 'allow'
                         and r.subject == subject and r.target == target), None)
        if shadowed is not None:
            outcome[access] = 'shadowed'
            report_once((key, 'shadowed'),
                        'NOT ADDED: policy line {} already has an identical allow, but '
                        'it is shadowed by an earlier {} rule at line {}:\n    {}\n'
                        '  The log reports an access to {} by {}. The existing rules '
                        'are kept, so the following rule was not added:\n    {}'.format(
                            shadowed.lineno, blocker.verdict, blocker.lineno,
                            policy_lines[blocker.idx].strip(), target, lib, allow_line))
            continue

        outcome[access] = 'added'
        queued.add(access)
        # Several libraries can share one pattern (libfoo.so.1, libfoo.so.2): the
        # rule has to go above the earliest of their blocking rules.
        if key not in new or blocker.idx < new[key].idx:
            new[key] = blocker

    for (subject, target), blocker in sorted(new.items()):
        if blocker.verdict == 'log':
            print('INFO: the allow for {} {} will shadow the log rule at policy '
                  'line {}:\n    {}\n  accesses matching it will no longer be '
                  'logged.'.format(subject, target, blocker.lineno,
                                   policy_lines[blocker.idx].strip()))

    new_lines = build_policy(policy_lines, new)
    verify(args.policy, rules, new_lines, entries, queued)

    for (subject, target), _blocker in sorted(new.items()):
        print(fmt(subject, target, 'allow'))

    counts = collections.Counter(outcome.values())
    rows = (
        ('already allowed by the policy', counts['already allowed']),
        ('allow rule added ({} line(s))'.format(len(new)), counts['added']),
        ('NOT added: deny/log rule for exactly this target', counts['exact']),
        ('NOT added: identical allow shadowed by a rule above', counts['shadowed']),
        ('NOT added: rule cannot be written (SKIPPED)', counts['skipped']),
    )
    print('\nSummary: {} unique access(es) in the logs'.format(len(entries)))
    for text, number in rows:
        print('  {:<54}{}'.format(text, number))
    print('  {:<54}{}'.format('unparsable log lines (UNPARSED, ignored)', unparsed))
    not_added = counts['exact'] + counts['shadowed'] + counts['skipped']
    if not_added or unparsed:
        print('  Some accesses are still denied or were not read, see the messages '
              'above.')

    if not new:
        print('nothing to insert')
        return

    if args.dry_run:
        print('dry run: {} new line(s) would be inserted into {}'.format(
            len(new), args.policy), file=sys.stderr)
        return

    with open(args.policy, 'w', encoding='utf-8') as fh:
        fh.write('\n'.join(new_lines) + '\n')
    print('inserted {} new line(s) into {}'.format(len(new), args.policy),
          file=sys.stderr)


if __name__ == '__main__':
    main()
