iamprover 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
iamprover/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.2.0"
iamprover/cli.py ADDED
@@ -0,0 +1,60 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+
6
+ from iamprover.engine.solver import check_all
7
+ from iamprover.invariants import load_invariants
8
+ from iamprover.model import ANONYMOUS_ARN, Principal
9
+ from iamprover.parsers.iam import load_account
10
+ from iamprover.parsers.terraform import load_tf_plan
11
+ from iamprover.report import render_json, render_text
12
+
13
+ EXIT_OK = 0
14
+ EXIT_ERROR = 1
15
+ EXIT_VIOLATIONS = 2
16
+
17
+
18
+ def main(argv: list[str] | None = None) -> int:
19
+ parser = argparse.ArgumentParser(
20
+ prog="iamprover",
21
+ description="Prove or refute security invariants over AWS IAM policies with Z3.",
22
+ )
23
+ sub = parser.add_subparsers(dest="command", required=True)
24
+
25
+ verify = sub.add_parser("verify", help="Verify invariants against an account or Terraform plan")
26
+ source = verify.add_mutually_exclusive_group(required=True)
27
+ source.add_argument("--account", help="Account description JSON (principals + policies)")
28
+ source.add_argument("--tf-plan", help="Terraform plan JSON (`terraform show -json plan`)")
29
+ verify.add_argument("--invariants", required=True, help="Invariant spec YAML")
30
+ verify.add_argument("--format", choices=["text", "json"], default="text")
31
+ verify.add_argument(
32
+ "--check-anonymous",
33
+ action="store_true",
34
+ help="Also verify invariants for an unauthenticated principal "
35
+ "(catches public resource-policy grants)",
36
+ )
37
+
38
+ args = parser.parse_args(argv)
39
+
40
+ try:
41
+ account = load_account(args.account) if args.account else load_tf_plan(args.tf_plan)
42
+ invariants = load_invariants(args.invariants)
43
+ except (OSError, ValueError, KeyError) as exc:
44
+ print(f"error: {exc}", file=sys.stderr)
45
+ return EXIT_ERROR
46
+
47
+ if args.check_anonymous:
48
+ account.principals.append(Principal(arn=ANONYMOUS_ARN, policies=[]))
49
+
50
+ if not invariants:
51
+ print("error: no invariants found in spec", file=sys.stderr)
52
+ return EXIT_ERROR
53
+
54
+ results = check_all(account, invariants)
55
+ print(render_json(results) if args.format == "json" else render_text(results))
56
+ return EXIT_OK if all(r.passed for r in results) else EXIT_VIOLATIONS
57
+
58
+
59
+ if __name__ == "__main__":
60
+ raise SystemExit(main())
File without changes
@@ -0,0 +1,64 @@
1
+ """Encode IAM Condition blocks as Z3 constraints over the request context.
2
+
3
+ Supported operators: StringEquals/NotEquals, StringLike/NotLike,
4
+ ArnEquals/ArnLike (and their Not variants), Bool, IpAddress/NotIpAddress
5
+ (IPv4). Anything else returns None ("unknown") and the caller substitutes a
6
+ sound default: True for Allow statements, False for Deny statements.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import ipaddress
12
+
13
+ import z3
14
+
15
+ from iamprover.engine.context import SOURCE_IP_KEY, Context
16
+ from iamprover.engine.patterns import matches_any
17
+ from iamprover.model import Condition
18
+
19
+
20
+ def _cidr_term(ctx: Context, value: str) -> z3.BoolRef | None:
21
+ try:
22
+ network = ipaddress.IPv4Network(value, strict=False)
23
+ except (ipaddress.AddressValueError, ValueError):
24
+ return None # IPv6 or malformed — unknown
25
+ ip = ctx.source_ip()
26
+ mask = int(network.netmask)
27
+ return (ip & mask) == int(network.network_address)
28
+
29
+
30
+ def encode_condition(cond: Condition, ctx: Context) -> z3.BoolRef | None:
31
+ op = cond.operator
32
+ negated = False
33
+ if op.startswith("StringNot") or op.startswith("ArnNot") or op == "NotIpAddress":
34
+ negated = True
35
+
36
+ if op in ("StringEquals", "StringNotEquals"):
37
+ var = ctx.string(cond.key)
38
+ term = z3.Or(*[var == z3.StringVal(v) for v in cond.values])
39
+ elif op in ("StringLike", "StringNotLike", "ArnLike", "ArnNotLike", "ArnEquals", "ArnNotEquals"):
40
+ term = matches_any(ctx.string(cond.key), cond.values)
41
+ elif op == "Bool":
42
+ var = ctx.string(cond.key)
43
+ term = z3.Or(*[var == z3.StringVal(v.lower()) for v in cond.values])
44
+ elif op in ("IpAddress", "NotIpAddress"):
45
+ if cond.key.lower() != SOURCE_IP_KEY:
46
+ return None
47
+ terms = [_cidr_term(ctx, v) for v in cond.values]
48
+ if any(t is None for t in terms):
49
+ return None
50
+ term = z3.Or(*terms)
51
+ else:
52
+ return None
53
+
54
+ return z3.Not(term) if negated else term
55
+
56
+
57
+ def encode_conditions(
58
+ conditions: list[Condition], ctx: Context, unknown_default: bool
59
+ ) -> z3.BoolRef:
60
+ terms = []
61
+ for cond in conditions:
62
+ term = encode_condition(cond, ctx)
63
+ terms.append(z3.BoolVal(unknown_default) if term is None else term)
64
+ return z3.And(*terms) if terms else z3.BoolVal(True)
@@ -0,0 +1,49 @@
1
+ """Request-context variables shared across one solver query.
2
+
3
+ Every condition key becomes a free Z3 variable: the solver searches over all
4
+ possible request contexts. `aws:SourceIp` is a 32-bit bitvector so CIDR
5
+ membership is exact; every other key is a string (IAM context values are
6
+ strings; Bool conditions compare against "true"/"false").
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import ipaddress
12
+
13
+ import z3
14
+
15
+ SOURCE_IP_KEY = "aws:sourceip"
16
+
17
+
18
+ class Context:
19
+ def __init__(self) -> None:
20
+ self.string_vars: dict[str, z3.SeqRef] = {}
21
+ self.ip_var: z3.BitVecRef | None = None
22
+
23
+ def string(self, key: str) -> z3.SeqRef:
24
+ key = key.lower()
25
+ if key not in self.string_vars:
26
+ self.string_vars[key] = z3.String(f"ctx[{key}]")
27
+ return self.string_vars[key]
28
+
29
+ def source_ip(self) -> z3.BitVecRef:
30
+ if self.ip_var is None:
31
+ self.ip_var = z3.BitVec(f"ctx[{SOURCE_IP_KEY}]", 32)
32
+ return self.ip_var
33
+
34
+ def constrain(self, key: str, value: str) -> z3.BoolRef:
35
+ """Pin a context key to a concrete value (invariant `where` clause)."""
36
+ if key.lower() == SOURCE_IP_KEY:
37
+ return self.source_ip() == int(ipaddress.IPv4Address(value))
38
+ return self.string(key) == z3.StringVal(value)
39
+
40
+ def assignments(self, model: z3.ModelRef) -> dict[str, str]:
41
+ """Extract the context values the solver chose for a counterexample."""
42
+ out: dict[str, str] = {}
43
+ decls = {d.name() for d in model.decls()}
44
+ for key, var in self.string_vars.items():
45
+ if var.decl().name() in decls:
46
+ out[key] = model[var].as_string()
47
+ if self.ip_var is not None and self.ip_var.decl().name() in decls:
48
+ out[SOURCE_IP_KEY] = str(ipaddress.IPv4Address(model[self.ip_var].as_long()))
49
+ return out
@@ -0,0 +1,65 @@
1
+ """Encode IAM policy-evaluation semantics as Z3 constraints.
2
+
3
+ Semantics modeled (v0.2): explicit Deny overrides Allow; default deny;
4
+ Action/NotAction and Resource/NotResource with `*`/`?` wildcards;
5
+ case-insensitive action matching; Condition blocks (supported subset — see
6
+ engine.conditions); same-account resource-based policies whose grants union
7
+ with identity-based allows. Unknown condition operators default to True on
8
+ Allow and False on Deny so permissions are only ever over-approximated.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import z3
14
+
15
+ from iamprover.engine.conditions import encode_conditions
16
+ from iamprover.engine.context import Context
17
+ from iamprover.engine.patterns import matches_any
18
+ from iamprover.model import Policy, Principal, Statement
19
+
20
+
21
+ def statement_matches(
22
+ stmt: Statement, action: z3.SeqRef, resource: z3.SeqRef, ctx: Context
23
+ ) -> z3.BoolRef:
24
+ if stmt.not_actions:
25
+ action_ok = z3.Not(matches_any(action, stmt.not_actions, case_insensitive=True))
26
+ else:
27
+ action_ok = matches_any(action, stmt.actions, case_insensitive=True)
28
+
29
+ if stmt.not_resources:
30
+ resource_ok = z3.Not(matches_any(resource, stmt.not_resources))
31
+ else:
32
+ resource_ok = matches_any(resource, stmt.resources)
33
+
34
+ condition_ok = encode_conditions(stmt.conditions, ctx, unknown_default=stmt.effect == "Allow")
35
+ return z3.And(action_ok, resource_ok, condition_ok)
36
+
37
+
38
+ def _grants_to(stmt: Statement, principal_arn: str) -> bool:
39
+ return "*" in stmt.principals or principal_arn in stmt.principals
40
+
41
+
42
+ def allowed(
43
+ principal: Principal,
44
+ action: z3.SeqRef,
45
+ resource: z3.SeqRef,
46
+ ctx: Context,
47
+ resource_policies: list[Policy] = (),
48
+ ) -> z3.BoolRef:
49
+ allow_terms = []
50
+ deny_terms = []
51
+ for policy in principal.policies:
52
+ for stmt in policy.statements:
53
+ term = statement_matches(stmt, action, resource, ctx)
54
+ (allow_terms if stmt.effect == "Allow" else deny_terms).append(term)
55
+
56
+ for policy in resource_policies:
57
+ for stmt in policy.statements:
58
+ if not _grants_to(stmt, principal.arn):
59
+ continue
60
+ term = statement_matches(stmt, action, resource, ctx)
61
+ (allow_terms if stmt.effect == "Allow" else deny_terms).append(term)
62
+
63
+ allows = z3.Or(*allow_terms) if allow_terms else z3.BoolVal(False)
64
+ denies = z3.Or(*deny_terms) if deny_terms else z3.BoolVal(False)
65
+ return z3.And(allows, z3.Not(denies))
@@ -0,0 +1,33 @@
1
+ """Compile IAM wildcard patterns (`*`, `?`) into Z3 regular expressions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import z3
6
+
7
+ _ANY_CHAR = z3.AllChar(z3.ReSort(z3.StringSort()))
8
+
9
+
10
+ def iam_pattern_to_re(pattern: str, case_insensitive: bool = False) -> z3.ReRef:
11
+ if case_insensitive:
12
+ pattern = pattern.lower()
13
+ parts: list[z3.ReRef] = []
14
+ literal = ""
15
+ for ch in pattern:
16
+ if ch in "*?":
17
+ if literal:
18
+ parts.append(z3.Re(z3.StringVal(literal)))
19
+ literal = ""
20
+ parts.append(z3.Star(_ANY_CHAR) if ch == "*" else _ANY_CHAR)
21
+ else:
22
+ literal += ch
23
+ if literal:
24
+ parts.append(z3.Re(z3.StringVal(literal)))
25
+ if not parts:
26
+ return z3.Re(z3.StringVal(""))
27
+ return parts[0] if len(parts) == 1 else z3.Concat(*parts)
28
+
29
+
30
+ def matches_any(value: z3.SeqRef, patterns: list[str], case_insensitive: bool = False) -> z3.BoolRef:
31
+ if not patterns:
32
+ return z3.BoolVal(False)
33
+ return z3.Or(*[z3.InRe(value, iam_pattern_to_re(p, case_insensitive)) for p in patterns])
@@ -0,0 +1,67 @@
1
+ """Check invariants against an account model; produce counterexamples on failure."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from fnmatch import fnmatch
7
+
8
+ import z3
9
+
10
+ from iamprover.engine.context import Context
11
+ from iamprover.engine.encoder import allowed
12
+ from iamprover.engine.patterns import matches_any
13
+ from iamprover.invariants import Invariant
14
+ from iamprover.model import Account
15
+
16
+
17
+ @dataclass
18
+ class Counterexample:
19
+ principal: str
20
+ action: str
21
+ resource: str
22
+ context: dict[str, str] = field(default_factory=dict)
23
+
24
+
25
+ @dataclass
26
+ class InvariantResult:
27
+ invariant: Invariant
28
+ passed: bool
29
+ counterexamples: list[Counterexample] = field(default_factory=list)
30
+
31
+
32
+ def _exempt(principal_arn: str, exemptions: list[str]) -> bool:
33
+ return any(fnmatch(principal_arn, pattern) for pattern in exemptions)
34
+
35
+
36
+ def check_invariant(account: Account, invariant: Invariant) -> InvariantResult:
37
+ result = InvariantResult(invariant=invariant, passed=True)
38
+ action = z3.String("action")
39
+ resource = z3.String("resource")
40
+
41
+ for principal in account.principals:
42
+ if _exempt(principal.arn, invariant.unless_principals):
43
+ continue
44
+ ctx = Context()
45
+ solver = z3.Solver()
46
+ # The action IAM evaluates is lowercased to model case-insensitive matching.
47
+ solver.add(matches_any(action, invariant.actions, case_insensitive=True))
48
+ solver.add(matches_any(resource, invariant.resources))
49
+ for key, value in invariant.where.items():
50
+ solver.add(ctx.constrain(key, value))
51
+ solver.add(allowed(principal, action, resource, ctx, account.resource_policies))
52
+ if solver.check() == z3.sat:
53
+ model = solver.model()
54
+ result.passed = False
55
+ result.counterexamples.append(
56
+ Counterexample(
57
+ principal=principal.arn,
58
+ action=model.eval(action, model_completion=True).as_string(),
59
+ resource=model.eval(resource, model_completion=True).as_string(),
60
+ context=ctx.assignments(model),
61
+ )
62
+ )
63
+ return result
64
+
65
+
66
+ def check_all(account: Account, invariants: list[Invariant]) -> list[InvariantResult]:
67
+ return [check_invariant(account, inv) for inv in invariants]
@@ -0,0 +1,57 @@
1
+ """Load invariant specs from YAML.
2
+
3
+ Spec format:
4
+
5
+ invariants:
6
+ - id: no-external-prod-read
7
+ description: Only the data-team role may read the prod data bucket
8
+ forbid:
9
+ actions: ["s3:GetObject", "s3:GetObject*"] # or singular `action`
10
+ resources: ["arn:aws:s3:::prod-data/*"] # or singular `resource`
11
+ unless_principal:
12
+ - "arn:aws:iam::111122223333:role/data-team" # exact or glob
13
+ where: # optional: pin request context
14
+ aws:MultiFactorAuthPresent: "false"
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+
22
+ import yaml
23
+
24
+
25
+ @dataclass
26
+ class Invariant:
27
+ id: str
28
+ description: str
29
+ actions: list[str]
30
+ resources: list[str]
31
+ unless_principals: list[str] = field(default_factory=list)
32
+ where: dict[str, str] = field(default_factory=dict)
33
+
34
+
35
+ def _plural(spec: dict, singular: str) -> list[str]:
36
+ values = spec.get(singular + "s", spec.get(singular))
37
+ if values is None:
38
+ raise ValueError(f"invariant forbid block needs '{singular}' or '{singular}s'")
39
+ return [values] if isinstance(values, str) else list(values)
40
+
41
+
42
+ def load_invariants(path: str | Path) -> list[Invariant]:
43
+ data = yaml.safe_load(Path(path).read_text(encoding="utf-8"))
44
+ invariants = []
45
+ for raw in data.get("invariants", []):
46
+ forbid = raw["forbid"]
47
+ invariants.append(
48
+ Invariant(
49
+ id=raw["id"],
50
+ description=raw.get("description", ""),
51
+ actions=_plural(forbid, "action"),
52
+ resources=_plural(forbid, "resource"),
53
+ unless_principals=list(raw.get("unless_principal", [])),
54
+ where={k: str(v) for k, v in raw.get("where", {}).items()},
55
+ )
56
+ )
57
+ return invariants
iamprover/model.py ADDED
@@ -0,0 +1,47 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+
5
+ ANONYMOUS_ARN = "anonymous"
6
+
7
+
8
+ @dataclass
9
+ class Condition:
10
+ operator: str # e.g. "StringEquals", "Bool", "IpAddress"
11
+ key: str # e.g. "aws:SourceIp"
12
+ values: list[str]
13
+
14
+
15
+ @dataclass
16
+ class Statement:
17
+ effect: str # "Allow" | "Deny"
18
+ actions: list[str] = field(default_factory=list)
19
+ not_actions: list[str] = field(default_factory=list)
20
+ resources: list[str] = field(default_factory=list)
21
+ not_resources: list[str] = field(default_factory=list)
22
+ conditions: list[Condition] = field(default_factory=list)
23
+ principals: list[str] = field(default_factory=list) # resource-based policies only
24
+
25
+
26
+ @dataclass
27
+ class Policy:
28
+ name: str
29
+ statements: list[Statement]
30
+
31
+
32
+ @dataclass
33
+ class Principal:
34
+ arn: str
35
+ policies: list[Policy]
36
+
37
+
38
+ @dataclass
39
+ class Account:
40
+ principals: list[Principal]
41
+ resource_policies: list[Policy] = field(default_factory=list)
42
+
43
+ def principal(self, arn: str) -> Principal:
44
+ for p in self.principals:
45
+ if p.arn == arn:
46
+ return p
47
+ raise KeyError(arn)
File without changes
@@ -0,0 +1,94 @@
1
+ """Parse AWS IAM policy documents into the internal model.
2
+
3
+ Modeling notes (v0.2):
4
+ - Condition blocks are parsed and encoded for supported operators (see
5
+ engine.conditions). Unsupported operators degrade safely: treated as
6
+ always-true on Allow statements and always-false on Deny statements, so the
7
+ analysis over-approximates permissions (false positives possible, no false
8
+ negatives within the modeled fragment).
9
+ - Resource-based policy `Principal` supports "*" and exact AWS principal ARNs.
10
+ NotPrincipal is not modeled.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from iamprover.model import Account, Condition, Policy, Principal, Statement
20
+
21
+
22
+ def _as_list(value: Any) -> list[str]:
23
+ if value is None:
24
+ return []
25
+ if isinstance(value, str):
26
+ return [value]
27
+ return list(value)
28
+
29
+
30
+ def parse_conditions(raw: dict) -> list[Condition]:
31
+ conditions = []
32
+ for operator, mapping in raw.items():
33
+ for key, values in mapping.items():
34
+ conditions.append(Condition(operator=operator, key=key, values=_as_list(values)))
35
+ return conditions
36
+
37
+
38
+ def parse_principals(raw: Any) -> list[str]:
39
+ if raw is None:
40
+ return []
41
+ if raw == "*":
42
+ return ["*"]
43
+ if isinstance(raw, dict):
44
+ principals = []
45
+ for kind, values in raw.items():
46
+ if kind == "AWS":
47
+ principals.extend(_as_list(values))
48
+ else:
49
+ principals.extend(f"{kind.lower()}:{v}" for v in _as_list(values))
50
+ return principals
51
+ return _as_list(raw)
52
+
53
+
54
+ def parse_statement(raw: dict) -> Statement:
55
+ return Statement(
56
+ effect=raw.get("Effect", "Deny"),
57
+ actions=_as_list(raw.get("Action")),
58
+ not_actions=_as_list(raw.get("NotAction")),
59
+ resources=_as_list(raw.get("Resource")) or ["*"],
60
+ not_resources=_as_list(raw.get("NotResource")),
61
+ conditions=parse_conditions(raw.get("Condition", {})),
62
+ principals=parse_principals(raw.get("Principal")),
63
+ )
64
+
65
+
66
+ def parse_policy_document(name: str, document: dict) -> Policy:
67
+ raw_statements = document.get("Statement", [])
68
+ if isinstance(raw_statements, dict):
69
+ raw_statements = [raw_statements]
70
+ return Policy(name=name, statements=[parse_statement(s) for s in raw_statements])
71
+
72
+
73
+ def load_account(path: str | Path) -> Account:
74
+ """Load an account description file.
75
+
76
+ Format:
77
+ {
78
+ "principals": [{"arn": "...", "policies": [{"name": "...", "document": {...}}]}],
79
+ "resource_policies": [{"name": "...", "document": {...}}]
80
+ }
81
+ """
82
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
83
+ principals = []
84
+ for p in data["principals"]:
85
+ policies = [
86
+ parse_policy_document(pol.get("name", "inline"), pol["document"])
87
+ for pol in p.get("policies", [])
88
+ ]
89
+ principals.append(Principal(arn=p["arn"], policies=policies))
90
+ resource_policies = [
91
+ parse_policy_document(pol.get("name", "resource-policy"), pol["document"])
92
+ for pol in data.get("resource_policies", [])
93
+ ]
94
+ return Account(principals=principals, resource_policies=resource_policies)
@@ -0,0 +1,106 @@
1
+ """Extract IAM policies from a Terraform plan (`terraform show -json plan > plan.json`).
2
+
3
+ v0.2 supports:
4
+ - inline policies: aws_iam_role_policy, aws_iam_user_policy
5
+ - managed policies (aws_iam_policy) linked via aws_iam_role_policy_attachment /
6
+ aws_iam_user_policy_attachment / aws_iam_policy_attachment — resolved by
7
+ policy ARN when known at plan time, else by configuration references
8
+ - resource-based policies: aws_s3_bucket_policy
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ from pathlib import Path
15
+
16
+ from iamprover.model import Account, Policy, Principal
17
+ from iamprover.parsers.iam import parse_policy_document
18
+
19
+ _INLINE_TYPES = {
20
+ "aws_iam_role_policy": ("role", "role"),
21
+ "aws_iam_user_policy": ("user", "user"),
22
+ }
23
+ _ATTACHMENT_TYPES = {
24
+ "aws_iam_role_policy_attachment": [("role", "role")],
25
+ "aws_iam_user_policy_attachment": [("user", "user")],
26
+ "aws_iam_policy_attachment": [("roles", "role"), ("users", "user")],
27
+ }
28
+
29
+
30
+ def _parse_doc(raw, name: str) -> Policy:
31
+ document = json.loads(raw) if isinstance(raw, str) else raw
32
+ return parse_policy_document(name, document)
33
+
34
+
35
+ def _config_references(plan: dict) -> dict[str, list[str]]:
36
+ """Map resource address -> addresses referenced by its policy_arn expression."""
37
+ refs: dict[str, list[str]] = {}
38
+ module = plan.get("configuration", {}).get("root_module", {})
39
+ for resource in module.get("resources", []):
40
+ expr = resource.get("expressions", {}).get("policy_arn", {})
41
+ refs[resource.get("address", "")] = expr.get("references", [])
42
+ return refs
43
+
44
+
45
+ def load_tf_plan(path: str | Path) -> Account:
46
+ plan = json.loads(Path(path).read_text(encoding="utf-8"))
47
+ principals: dict[str, Principal] = {}
48
+ resource_policies: list[Policy] = []
49
+ managed_by_arn: dict[str, Policy] = {}
50
+ managed_by_address: dict[str, Policy] = {}
51
+ attachments: list[tuple[str, dict, str]] = [] # (address, after, rtype)
52
+
53
+ def principal_for(arn: str) -> Principal:
54
+ return principals.setdefault(arn, Principal(arn=arn, policies=[]))
55
+
56
+ for rc in plan.get("resource_changes", []):
57
+ rtype = rc.get("type")
58
+ change = rc.get("change") or {}
59
+ after = change.get("after")
60
+ if not after or "delete" in change.get("actions", []):
61
+ continue
62
+
63
+ if rtype in _INLINE_TYPES:
64
+ attr, kind = _INLINE_TYPES[rtype]
65
+ name, policy_json = after.get(attr), after.get("policy")
66
+ if name and policy_json:
67
+ policy = _parse_doc(policy_json, after.get("name", rc.get("address", "inline")))
68
+ principal_for(f"tf:{kind}/{name}").policies.append(policy)
69
+
70
+ elif rtype == "aws_iam_policy":
71
+ policy_json = after.get("policy")
72
+ if policy_json:
73
+ policy = _parse_doc(policy_json, after.get("name", rc.get("address", "managed")))
74
+ managed_by_address[rc.get("address", "")] = policy
75
+ if after.get("arn"):
76
+ managed_by_arn[after["arn"]] = policy
77
+
78
+ elif rtype in _ATTACHMENT_TYPES:
79
+ attachments.append((rc.get("address", ""), after, rtype))
80
+
81
+ elif rtype == "aws_s3_bucket_policy":
82
+ policy_json = after.get("policy")
83
+ if policy_json:
84
+ resource_policies.append(
85
+ _parse_doc(policy_json, after.get("bucket", rc.get("address", "bucket-policy")))
86
+ )
87
+
88
+ references = _config_references(plan)
89
+ for address, after, rtype in attachments:
90
+ policy = managed_by_arn.get(after.get("policy_arn") or "")
91
+ if policy is None:
92
+ for ref in references.get(address, []):
93
+ base = ref.removesuffix(".arn")
94
+ if base in managed_by_address:
95
+ policy = managed_by_address[base]
96
+ break
97
+ if policy is None:
98
+ continue
99
+ for attr, kind in _ATTACHMENT_TYPES[rtype]:
100
+ value = after.get(attr)
101
+ names = value if isinstance(value, list) else [value]
102
+ for name in names:
103
+ if name:
104
+ principal_for(f"tf:{kind}/{name}").policies.append(policy)
105
+
106
+ return Account(principals=list(principals.values()), resource_policies=resource_policies)
iamprover/report.py ADDED
@@ -0,0 +1,47 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+
5
+ from iamprover.engine.solver import InvariantResult
6
+
7
+
8
+ def render_text(results: list[InvariantResult]) -> str:
9
+ lines = []
10
+ for res in results:
11
+ status = "PASS" if res.passed else "FAIL"
12
+ lines.append(f"[{status}] {res.invariant.id} — {res.invariant.description}")
13
+ for ce in res.counterexamples:
14
+ lines.append(f" counterexample: {ce.principal}")
15
+ lines.append(f" can perform {ce.action}")
16
+ lines.append(f" on resource {ce.resource}")
17
+ if ce.context:
18
+ pairs = ", ".join(f"{k} = {v}" for k, v in sorted(ce.context.items()))
19
+ lines.append(f" with context {pairs}")
20
+ failed = sum(1 for r in results if not r.passed)
21
+ lines.append("")
22
+ lines.append(
23
+ f"{len(results) - failed}/{len(results)} invariants proven"
24
+ + (f", {failed} violated" if failed else " — no violations")
25
+ )
26
+ return "\n".join(lines)
27
+
28
+
29
+ def render_json(results: list[InvariantResult]) -> str:
30
+ payload = [
31
+ {
32
+ "id": res.invariant.id,
33
+ "description": res.invariant.description,
34
+ "passed": res.passed,
35
+ "counterexamples": [
36
+ {
37
+ "principal": ce.principal,
38
+ "action": ce.action,
39
+ "resource": ce.resource,
40
+ "context": ce.context,
41
+ }
42
+ for ce in res.counterexamples
43
+ ],
44
+ }
45
+ for res in results
46
+ ]
47
+ return json.dumps(payload, indent=2)
@@ -0,0 +1,126 @@
1
+ Metadata-Version: 2.4
2
+ Name: iamprover
3
+ Version: 0.2.0
4
+ Summary: Formally verify security invariants over AWS IAM policies using an SMT solver (Z3), with counterexample traces.
5
+ Project-URL: Homepage, https://github.com/utkarsh698/iamprover
6
+ Author-email: Utkarsh Batham <udaydeepak1928@gmail.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Keywords: aws,cspm,formal-verification,iam,policy,security,smt,z3
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: System Administrators
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Security
15
+ Requires-Python: >=3.10
16
+ Requires-Dist: pyyaml>=6.0
17
+ Requires-Dist: z3-solver>=4.12
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest>=8.0; extra == 'dev'
20
+ Requires-Dist: ruff>=0.4; extra == 'dev'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # iamprover
24
+
25
+ **Formally verify security invariants over AWS IAM policies — with proofs, not pattern-matching.**
26
+
27
+ Most IAM scanners grep for known misconfigurations. `iamprover` does something stronger: it encodes
28
+ IAM policy-evaluation semantics into an SMT solver ([Z3](https://github.com/Z3Prover/z3)) and
29
+ **proves** that your declared security invariants hold — or hands you a **concrete counterexample**
30
+ (principal, action, resource) showing exactly how they break.
31
+
32
+ ```
33
+ [FAIL] prod-data-read-restricted — Only the data-team role may read the prod-data bucket
34
+ counterexample: arn:aws:iam::111122223333:role/ci-runner
35
+ can perform s3:getobject
36
+ on resource arn:aws:s3:::prod-data/A
37
+
38
+ [PASS] audit-logs-untouchable — No principal may perform any S3 action on the audit-logs bucket
39
+ [PASS] no-iam-mutation — No principal may mutate IAM (privilege-escalation surface)
40
+
41
+ 2/3 invariants proven, 1 violated
42
+ ```
43
+
44
+ The `[PASS]` lines are not "no findings" — they are proofs over *all* possible actions and
45
+ resources, including every wildcard expansion.
46
+
47
+ ## Why
48
+
49
+ Individually-correct IAM policies compose into globally-unsafe states: a broad `s3:Get*` on one
50
+ role quietly bypasses the least-privilege story your prod bucket policy tells. This tool grew out
51
+ of research on exactly that failure mode —
52
+ [*Security Invariants in Distributed Cloud Systems*](https://doi.org/10.5281/zenodo.20099386),
53
+ which model-checks how per-service security enforcement breaks under cross-service composition.
54
+ `iamprover` applies the same idea to real cloud policies: declare system-level invariants, verify
55
+ them mechanically, get violation traces when they fail.
56
+
57
+ ## Install
58
+
59
+ ```bash
60
+ pip install iamprover
61
+ ```
62
+
63
+ ## Quickstart
64
+
65
+ 1. Describe your principals and their policies (or point at a Terraform plan):
66
+
67
+ ```bash
68
+ iamprover verify --account examples/account.json --invariants examples/invariants.yaml
69
+ ```
70
+
71
+ 2. Or gate a Terraform change in CI:
72
+
73
+ ```bash
74
+ terraform show -json plan > plan.json
75
+ iamprover verify --tf-plan plan.json --invariants invariants.yaml # exit 2 on violation
76
+ ```
77
+
78
+ Invariants are declared in YAML:
79
+
80
+ ```yaml
81
+ invariants:
82
+ - id: prod-data-read-restricted
83
+ description: Only the data-team role may read objects in the prod-data bucket
84
+ forbid:
85
+ action: "s3:GetObject"
86
+ resource: "arn:aws:s3:::prod-data/*"
87
+ unless_principal:
88
+ - "arn:aws:iam::111122223333:role/data-team"
89
+ ```
90
+
91
+ ## What is modeled (v0.2)
92
+
93
+ - Allow/Deny with explicit-deny-overrides-allow and default deny
94
+ - `Action` / `NotAction` / `Resource` / `NotResource` with `*` and `?` wildcards
95
+ - Case-insensitive action matching (as IAM does it)
96
+ - `Condition` blocks: `StringEquals/Like` (and Not/Arn variants), `Bool`, `IpAddress`/`NotIpAddress`
97
+ (IPv4 CIDR, exact via bitvector encoding). The solver searches over all request contexts and
98
+ counterexamples include the context (`with context aws:multifactorauthpresent = true, …`);
99
+ invariants can pin context with a `where:` clause
100
+ - Resource-based policies (e.g. bucket policies) with `Principal: "*"` or exact ARNs, unioned with
101
+ identity-based grants; `--check-anonymous` verifies invariants for an unauthenticated principal
102
+ (catches public grants)
103
+ - Terraform plans: inline policies, managed policies via attachments (resolved by ARN or
104
+ configuration reference), and `aws_s3_bucket_policy`
105
+ - Invariant exemptions by exact ARN or glob
106
+
107
+ **Soundness note:** unsupported condition operators degrade safely — treated as always-true on
108
+ Allow and always-false on Deny — so permissions are only ever over-approximated: iamprover may
109
+ flag violations a condition would prevent (false positives), but within the modeled fragment it
110
+ will not miss one (no false negatives). Trust the `PASS`es; investigate the `FAIL`s.
111
+
112
+ ## Roadmap
113
+
114
+ - **v0.3** — GitHub Action on the Marketplace · privilege-escalation chain detection (`iam:PassRole` → `lambda:CreateFunction`, `iam:CreateAccessKey`, …) as built-in invariants
115
+ - **v0.4** — live-account ingestion via `aws iam get-account-authorization-details` · cross-account trust analysis · policy variables and tag-based conditions
116
+
117
+ ## Development
118
+
119
+ ```bash
120
+ pip install -e ".[dev]"
121
+ pytest
122
+ ```
123
+
124
+ ## License
125
+
126
+ Apache-2.0
@@ -0,0 +1,19 @@
1
+ iamprover/__init__.py,sha256=Zn1KFblwuFHiDRdRAiRnDBRkbPttWh44jKa5zG2ov0E,22
2
+ iamprover/cli.py,sha256=rdpZVSDzdJuAF5fZb6v05imuZHi3ZzTwE4DgBP7oRfc,2220
3
+ iamprover/invariants.py,sha256=eY1J5MsbPiyeSI8T9Jv63KSr-WnCPE_FFCnI0OMey9g,1877
4
+ iamprover/model.py,sha256=rvYIqJn6CcqRyQV1eMQKkwc7LghhqQXk-UEX_t_MdKA,1130
5
+ iamprover/report.py,sha256=rAFTyWCHATpVymRiHNWNi7Yw_qN5aRP0sUabfXOuHkQ,1603
6
+ iamprover/engine/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ iamprover/engine/conditions.py,sha256=Cqy3TJ4KQQ4nBoruyNcVGEvVh1NaOmZRrTy_NopZoXU,2288
8
+ iamprover/engine/context.py,sha256=I8u8JxoXu6sTwAUPKddwVRuf5F1enTd8CqdcGHPzdgM,1835
9
+ iamprover/engine/encoder.py,sha256=Z-Zz9ZW_h3JeHJZBiOLkq4rABWlxAnnNErbmHkRKauw,2452
10
+ iamprover/engine/patterns.py,sha256=hU4IwsUpOwpCC9HAOtLwtXsPOv00058qC1EYrqrb7rI,1074
11
+ iamprover/engine/solver.py,sha256=K_fXcLQfqYTGXOhpHbx3gnSAWpv6D7JFXIE73L6bjUU,2323
12
+ iamprover/parsers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
+ iamprover/parsers/iam.py,sha256=RKbS2fuo9pckZEIoibiuYMYEtiUqHzdUm2XrTYahwC4,3212
14
+ iamprover/parsers/terraform.py,sha256=7_OLXfeKOdHYptPHnzGUElh8uDhz83W4BanRq4jP-PQ,4260
15
+ iamprover-0.2.0.dist-info/METADATA,sha256=I5PubG9WeG-kdGMbM7RclHoIrVabAhp8jA14pCo_fSI,5081
16
+ iamprover-0.2.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
17
+ iamprover-0.2.0.dist-info/entry_points.txt,sha256=iS16onJadyemv5DlUXGdMJ4baEkyTVJkELeJ7kh4ubo,49
18
+ iamprover-0.2.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
19
+ iamprover-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ iamprover = iamprover.cli:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.