1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
|
#!/usr/bin/env python3
# Copyright 2014-2015, Tresys Technology, LLC
#
# SPDX-License-Identifier: GPL-2.0-only
#
import sys
import argparse
import logging
import signal
import warnings
import networkx as nx
import setools
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
parser = argparse.ArgumentParser(
description="SELinux policy domain transition analysis tool.",
epilog="If no analysis is selected, all forward transitions out of the source will be printed.")
parser.add_argument("--version", action="version", version=setools.__version__)
parser.add_argument("-p", "--policy", help="Path to SELinux policy to analyze.")
parser.add_argument("-s", "--source", help="Source type of the analysis.", required=True)
parser.add_argument("-t", "--target", help="Target type of the analysis.")
parser.add_argument("--full", help="Print rule lists for transitions.", action="store_true")
parser.add_argument("--stats", action="store_true",
help="Display statistics at the end of the analysis.")
parser.add_argument("-v", "--verbose", action="store_true",
help="Print extra informational messages")
parser.add_argument("--debug", action="store_true", dest="debug", help="Enable debugging.")
alg = parser.add_argument_group("Analysis algorithm")
alg.add_argument("-S", "--shortest_path", action="store_true",
help="Calculate all shortest paths.")
alg.add_argument("-A", "--all_paths", type=int, metavar="MAX_STEPS",
help="Calculate all paths, with the specified maximum path length. (Expensive)")
opts = parser.add_argument_group("Analysis options")
opts.add_argument("-r", "--reverse", action="store_true", default=False,
help="Perform a reverse DTA.")
opts.add_argument("-l", "--limit_trans", default=0, type=int,
help="Limit to the specified number of transitions. Default is unlimited.")
opts.add_argument("-o", "--output_file", help="Output file for graphical results, PNG format.")
opts.add_argument("exclude", help="List of excluded types in the analysis.", nargs="*")
args = parser.parse_args()
if not args.target and (args.shortest_path or args.all_paths):
parser.error("The target type must be specified to determine a path.")
if args.target and not (args.shortest_path or args.all_paths):
parser.error("An algorithm must be specified to determine a path.")
if args.debug:
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s|%(levelname)s|%(name)s|%(message)s')
if not sys.warnoptions:
warnings.simplefilter("default")
elif args.verbose:
logging.basicConfig(level=logging.INFO, format='%(message)s')
if not sys.warnoptions:
warnings.simplefilter("default")
else:
logging.basicConfig(level=logging.WARNING, format='%(message)s')
if not sys.warnoptions:
warnings.simplefilter("ignore")
try:
p = setools.SELinuxPolicy(args.policy)
g = setools.DomainTransitionAnalysis(p, exclude=args.exclude)
pathnum: int = 0
path: setools.DTAPath
stepnum: int = 0
step: setools.DomainTransition
if args.shortest_path or args.all_paths:
g.source = args.source
g.target = args.target
g.reverse = args.reverse
if args.shortest_path:
g.mode = setools.DomainTransitionAnalysis.Mode.ShortestPaths
else:
g.mode = setools.DomainTransitionAnalysis.Mode.AllPaths
g.depth_limit = args.all_paths
if args.output_file:
pgv = nx.nx_agraph.to_agraph(g.graphical_results())
pgv.draw(path=args.output_file, prog="dot", format="png")
else:
for pathnum, path in enumerate(g.results(), start=1): # type: ignore
print(f"Domain transition path {pathnum}:")
for stepnum, step in enumerate(path, start=1):
if args.full:
print(f"Step {stepnum}: {step:full}\n")
else:
print(f"Step {stepnum}: {step}")
if args.limit_trans and pathnum >= args.limit_trans:
break
print()
print(f"\n{pathnum} domain transition path(s) found.")
else: # single transition
if args.reverse:
g.mode = setools.DomainTransitionAnalysis.Mode.TransitionsIn
g.target = args.source
else:
g.mode = setools.DomainTransitionAnalysis.Mode.TransitionsOut
g.source = args.source
if args.output_file:
pgv = nx.nx_agraph.to_agraph(g.graphical_results())
pgv.draw(path=args.output_file, prog="dot", format="png")
else:
for pathnum, step in enumerate(g.results(), start=1): # type: ignore
if args.full:
print(f"Transition {pathnum}: {step:full}\n")
else:
print(f"Transition {pathnum}: {step}")
if args.limit_trans and pathnum >= args.limit_trans:
break
print(f"\n{pathnum} domain transition(s) found.")
if args.stats:
print("\nGraph statistics:")
print(g.get_stats())
except AssertionError:
# Always provide a traceback for assertion errors
raise
except Exception as err:
if args.debug:
raise
else:
print(err)
sys.exit(1)
|