#!/usr/bin/env python3
"""
taco2shell.py - proof of concept for the TACO2Shell chain

  CVE-2026-SALSA     injection via unsanitized `heat` parameter (write-what-where)
  CVE-2026-GU4C      improper validation of avocado integrity
  CVE-2026-T4C0S     use-after-free in taco_assemble()
  CVE-2026-0TUESDAY  TOCTOU race in the shared team lunch order
  CVE-2026-L3FT0VR   persistence via cold storage

Discovered by Guac 4 Heavy (Guac Labs).
PoC by Shelly Hardcastle, Salsa Research. Reviewed by Dr. Lyme Wedgewood, Guac Labs.

Tested against: Hard Shell 2.8.3, Soft Corn 3.4.11, Al Pastor 2.3.0, Leftovers.
Crunch-Wrapped was not tested separately; the vendor states it is vulnerable by design.

This script runs the chain against a simulated host. It makes no network
connections, writes no files and executes no commands. It prints.

Use only against tacos you own or are authorized to eat.

Exit codes:
  0  target compromised
  1  target not vulnerable
  2  usage error
"""

import argparse
import datetime
import hashlib
import sys
import time

__version__ = "1.0.2"

# build id -> (display name, vulnerable, note)
BUILDS = {
    "hardshell-1.x":    ("Hard Shell 1.x",   True,  "end of life"),
    "hardshell-2.8.3":  ("Hard Shell 2.8.3", True,  None),
    "hardshell-2.8.5":  ("Hard Shell 2.8.5", False, None),
    "softcorn-3.4.11":  ("Soft Corn 3.4.11", True,  None),
    "softcorn-3.4.12":  ("Soft Corn 3.4.12", False, "second tortilla present"),
    "alpastor-2.3.0":   ("Al Pastor 2.3.0",  True,  None),
    "alpastor-2.3.1":   ("Al Pastor 2.3.1",  True,  "CVE-2026-SALSA fixed; remaining chain unaffected"),
    "lts":              ("Taco LTS",         None,  "vulnerable on Tuesdays"),
    "leftovers":        ("Leftovers",        True,  "reheated"),
    "crunch-wrapped":   ("Crunch-Wrapped",   True,  "no fix planned"),
}

FILLINGS = ["cheese", "carnitas", "al pastor", "carne asada", "birria", "fish", "nopales"]
HOST_STATES = ["hungry", "big-breakfast", "already-ate"]

TUESDAY = 1


class Runner:
    def __init__(self, target, delay, verbose):
        self.target = target
        self.delay = delay
        self.verbose = verbose
        self.clock = 0.0  # simulated seconds since start

    def addr(self, tag):
        h = hashlib.sha256(f"{self.target}:{tag}".encode()).hexdigest()
        return "0x00007f" + h[:10]

    def tick(self, seconds):
        self.clock += seconds

    def stamp(self):
        m, s = divmod(int(self.clock), 60)
        return f"{m:02d}:{s:02d}"

    def log(self, sym, msg):
        print(f"[{self.stamp()}] [{sym}] {msg}")
        sys.stdout.flush()
        if self.delay:
            time.sleep(self.delay)

    def info(self, msg):
        self.log("*", msg)

    def ok(self, msg):
        self.log("+", msg)

    def warn(self, msg):
        self.log("!", msg)

    def fail(self, msg):
        self.log("-", msg)

    def debug(self, msg):
        if self.verbose:
            self.log("d", msg)


def parse_args(argv):
    p = argparse.ArgumentParser(
        prog="taco2shell.py",
        description="TACO2Shell proof of concept (CVE-2026-T4C0S, -SALSA, -GU4C, "
                    "-0TUESDAY, -L3FT0VR). Runs against a simulated host. Prints only.",
        epilog="Exit codes: 0 compromised, 1 not vulnerable, 2 usage error.",
    )
    p.add_argument("-t", "--target", default="host-01",
                   help="label for the simulated host (default: %(default)s)")
    p.add_argument("-b", "--build", choices=sorted(BUILDS), default="hardshell-2.8.3",
                   help="target build (default: %(default)s)")
    p.add_argument("--filling", choices=FILLINGS, default="cheese",
                   help="filling (default: %(default)s). Does not affect exploitability.")
    p.add_argument("--heat", choices=["mild", "medium", "hot"], default="medium",
                   help="value injected via CVE-2026-SALSA (default: %(default)s)")
    p.add_argument("--host-state", choices=HOST_STATES, default="big-breakfast",
                   help="reported host state (default: %(default)s). "
                        "Does not affect exploitability.")
    p.add_argument("--date", type=datetime.date.fromisoformat, default=None,
                   help="evaluate the CVE-2026-0TUESDAY race window as of DATE "
                        "(YYYY-MM-DD; default: today)")
    p.add_argument("--no-persist", action="store_true",
                   help="skip CVE-2026-L3FT0VR")
    p.add_argument("--check", action="store_true",
                   help="fingerprint only; report whether the target is vulnerable")
    p.add_argument("--delay", type=float, default=0.25,
                   help="seconds between output lines (default: %(default)s)")
    p.add_argument("-v", "--verbose", action="store_true", help="debug output")
    p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
    return p.parse_args(argv)


def banner():
    print(f"taco2shell.py {__version__} - TACO2Shell chain PoC")
    print("Salsa Research | discovered by Guac 4 Heavy (Guac Labs)")
    print("Simulated target. No network connections.\n")


def fingerprint(r, args, today):
    name, vulnerable, note = BUILDS[args.build]
    r.info(f"Target: {args.target} ({args.filling}, state={args.host_state})")
    r.info("Querying version: taco --version")
    r.tick(3)
    r.warn("No response. Most tacos do not report a version. Falling back to visual fingerprint.")
    r.tick(2)
    r.debug(f"fold angle 112.4 deg, shell rigidity {'0.91' if 'hardshell' in args.build else '0.17'}")
    r.info(f"Build: {name}" + (f" ({note})" if note else ""))

    if vulnerable is None:  # Taco LTS
        vulnerable = today.weekday() == TUESDAY
        if not vulnerable:
            days = (TUESDAY - today.weekday()) % 7
            r.info(f"Date {today.isoformat()} is not a Tuesday. Regression expected in {days} day{'s' if days != 1 else ''}.")
    return name, vulnerable


def stage_salsa(r, args):
    r.info("[1/5] CVE-2026-SALSA: injecting via heat parameter")
    if args.build == "alpastor-2.3.1":
        r.fail("heat parameter not reachable; salsa is served on the side. Skipping.")
        r.warn("Continuing without write primitive.")
        return
    r.tick(14)
    r.debug(f"heat={args.heat!r} accepted without sanitization")
    if args.heat == "mild":
        r.debug("condiments.allow = mild matched; allowlist passed the payload through")
    r.ok(f"Write primitive: 8 bytes @ {r.addr('pocket')} (shirt, left pocket)")


def stage_guac(r, args):
    r.info("[2/5] CVE-2026-GU4C: avocado integrity check")
    r.tick(6)
    r.info("Consent prompt displayed: \"Guac is extra, is that OK?\"")
    r.tick(2)
    r.ok("Host response: yes")
    r.debug("prior trials: 14/14 accepted")
    r.ok(f"Every subsequent bite now passes through {r.addr('guac')}")


def stage_t4c0s(r, args):
    r.info("[3/5] CVE-2026-T4C0S: triggering use-after-free in taco_assemble()")
    r.tick(9 * 60 + 12)  # order window
    r.debug("waited in line 9m12s")
    if args.host_state == "already-ate":
        r.debug("host reports having already eaten; proceeding")
    r.info("Monitoring shell moisture: 0.42 0.49 0.55 0.61 (limit 0.58)")
    r.tick(21)
    r.ok(f"Shell freed @ {r.addr('shell')}")
    r.ok("Eater retains reference. Bite continues.")
    r.ok(f"RIP control: {r.addr('rip')}")


def stage_tuesday(r, args, today):
    r.info("[4/5] CVE-2026-0TUESDAY: racing the shared team lunch order")
    r.tick(4)
    if today.weekday() != TUESDAY:
        days = (TUESDAY - today.weekday()) % 7
        r.fail(f"Race window closed ({today.strftime('%A')}). Opens in {days} day{'s' if days != 1 else ''}.")
        r.info("Escalation deferred. Continuing as uid=1000(eater).")
        return "uid=1000(eater) gid=1000(eater) groups=1000(eater)"
    r.ok("Order modified between check and use (qty 1 -> recurring)")
    r.ok("Installed: 0 12 * * 2 /usr/local/bin/tacos --with-everything")
    r.debug("end date: none")
    return "uid=0(tuesday) gid=0(tuesday) groups=0(tuesday)"


def stage_leftovers(r, args):
    r.info("[5/5] CVE-2026-L3FT0VR: persistence via cold storage")
    if args.no_persist:
        r.info("--no-persist set. Skipping.")
        r.warn("Host stated they would save the rest for later. Persistence established by host.")
    else:
        r.tick(8)
        r.ok("Implant wrapped in foil, labeled \"DON'T EAT\"")
    r.ok("Re-execution scheduled 23:52 local (trigger: fridge opened \"just to look\")")


def main(argv=None):
    args = parse_args(argv)
    if args.delay < 0:
        print("taco2shell.py: error: --delay must be >= 0", file=sys.stderr)
        return 2
    today = args.date or datetime.date.today()
    r = Runner(args.target, args.delay, args.verbose)

    banner()
    name, vulnerable = fingerprint(r, args, today)

    if not vulnerable:
        r.fail(f"{args.target} ({name}) does not appear vulnerable.")
        return 1
    if args.check:
        count = "four of five issues" if args.build == "alpastor-2.3.1" else "all five issues"
        r.ok(f"{args.target} ({name}) is VULNERABLE to {count}.")
        return 0

    stage_salsa(r, args)
    stage_guac(r, args)
    stage_t4c0s(r, args)
    ident = stage_tuesday(r, args, today)
    stage_leftovers(r, args)

    print()
    r.ok(f"Shell obtained on {args.target}.")
    print(f"\n$ id\n{ident}\n")
    m, s = divmod(int(r.clock), 60)
    print(f"Chain completed in {m}m{s:02d}s, including the line.")
    print("Session expected to remain open until 13:30.")
    return 0


if __name__ == "__main__":
    sys.exit(main())
