Creating a Single Safety Gate  Using AWS Lambda, DynamoDB and LocalStack.

Creating a Single Safety Gate Using AWS Lambda, DynamoDB and LocalStack.

Build one safety gate instead: an AWS Lambda function checks a DynamoDB table of approved targets and answers allow or deny. If allowed, it returns the exact command to run, and a small caller script runs only that. Deploy it free on LocalStack, watch the same command get blocked and then allowed by changing one record, and learn where the pattern still falls short.

The problem: scripts that run commands against whatever you give them

Say you have a few scripts that run ping, dig, or a port scan against hosts. Each script takes a hostname and runs the command.
Nothing in that setup asks whether you're allowed to test that host. One typo, a stale hostname list, or a script pointed at production instead of staging, and the command runs. If those scripts are security tools, the target may be a system you have no permission to touch.
The usual fix is to add an "is this host allowed?" check to each script. That works until you have ten scripts. Then you have ten copies of the check, and one of them is outdated or missing. Nobody notices until it matters.

The idea: one gate that makes the decision

A single gate is one service that answers one question: "May this tool run against this target?" Scripts don't decide for themselves. They ask the gate, and they run a command only if the gate gives them one.

Without a gate

With a single gate

script A ──►
runs ping on host
script A ─┐

script B ──►
runs dig on host command
script B ─┼─►
GATE ──► allow + exact
script C ──►
runs ping on host (each decides alone, or doesn't)
script C ─┘
└──► deny + reason (one place decides; scripts just ask)

The rules live in one place. To approve or revoke a target, you change one record, not ten scripts.

What the gate has to do

Starting from the failure above, the gate needs to:
  1. Know which targets are approved. This needs one list that all scripts share.
  1. Refuse by default. A host that isn't on the list, or a request missing a field, is denied. "Not found" never means "allowed."
  1. Never accept a command from the caller. If a script can send rm -rf / as the tool, the gate becomes a way to run anything. Callers send a short name like ping, and the gate maps it to a fixed command.
  1. Return a command the caller can't alter. The gate returns an argument list, such as ["ping","-c","3","host"], not a string for a shell to parse. A shell string can be tricked with host; rm -rf /. An argument list can't.
  1. Leave a record. Every decision is logged, so you can see what was allowed and what was blocked.

The architecture

Need
Component
Why this one
Shared list of approved targets
DynamoDB table scope
One lookup by hostname. Changing a record takes effect immediately for every caller.
One place that decides
Lambda function safety-gate
A small function with no server to run. Callers invoke it by name.
Permissions for the gate function
IAM role gate-lambda-role
Lets the Lambda run and write logs.
Fixed name-to-command map
A dictionary in the Lambda
The only place commands are defined.
A caller that obeys the gate
run-with-gate.py
Asks the gate, then runs only the argument list it returns.

run-with-gate.py ping 127.0.0.1
│ {"tool":"ping","target":"127.0.0.1"}
▼
Lambda: safety-gate
│ 1. tool name in the fixed map? no → DENY
│ 2. target in DynamoDB? no → DENY
│ 3. authorized == true? no → DENY
▼
ALLOW → {"argv": ["ping","-c","3","127.0.0.1"]}
▼
run-with-gate.py runs that exact list (no shell)


To try this without an AWS account or any cost, the repo runs the stack on LocalStack, a separate project that emulates AWS APIs on your machine. It isn't an AWS product. The pattern doesn't depend on it: the same function and table work on real AWS.

Build it

You need:
  • A container engine, Docker or Podman. LocalStack runs in a container, and it starts each Lambda in its own container, so it needs access to your engine.
  • AWS CLI v2.
  • Python 3, for the caller script.
  • curl, which the start script uses to check LocalStack's health.

git clone https://github.com/Chimelijah/safetyhack.git
cd safetyhack
chmod +x *.sh run-with-gate.py
./start-localstack.sh


The script starts a container named  localstack-demo  and polls until LocalStack answers. The first run can take a while because it downloads the image. When it's ready, it prints a list of services. For this demo you need  dynamodb ,  iam ,  lambda , and  logs  to show  "available" :
{"services": {"dynamodb": "available", "iam": "available", "lambda": "available", "logs": "available", ...}, "edition": "community", "version": "3.0.2"}


If it fails with a connection error instead, go to Troubleshooting. Otherwise deploy:

./deploy.sh


This creates the  scope  table, the  gate-lambda-role role , and the  safety-gate  Lambda. It also seeds one record:  demo.example.internal  with  authorized: true . A new Lambda doesn't work immediately. It starts as  Pending  and becomes  Active  after a few seconds. The script waits for you, checking every 2 seconds for up to about 60 seconds, and stops with an error if the function reports  Failed :

=== waiting for it to go active ===
state: Pending
state: Pending
state: Active
=== done. Run ./test.sh to try it. ===


The number of  Pending  lines varies. When you see  done,  the function is ready. If you invoke a function by hand while it's  Pending , AWS returns  ResourceConflictException . Real AWS behaves the same way, so a deploy pipeline should also wait for  Active  before it sends traffic.
Incase the scripts turn off the AWS CLI pager which you will notice by the moment the CLI stops partway through long JSON output and waits for you to press  q,  which looks like a hang.

Why the order of checks matters

The gate's logic fits in a few lines, and the order is the whole design:
if not target or not tool:
return _deny("target and tool are both required")
if tool not in ALLOWED_TOOLS:
return _deny(f"unknown tool: {tool}")
item = table.get_item(Key={"target": target}).get("Item")
if item is None:
return _deny("... not in the authorized scope table")
if not item.get("authorized", False):
return _deny("... recorded but explicitly NOT authorized")
return {"decision": "allow", "argv": ALLOWED_TOOLS[tool] + [target], ...}


  • The tool check comes before the database lookup. A bad tool name is rejected without touching the database.
  • Missing and unauthorized are separate denials. You can record a host you've decided not to test, instead of leaving it as an unknown.
  • allow is the last line. Every other path ends in a denial.
  • argv is the fixed map plus the target. The caller never supplies a command token.

Verify the gate

./test.sh


Each test prints a  StatusCode  block from the Lambda invoke call, then the gate's decision. Real output from a clean run:

=== 1. authorized target -> should ALLOW ===
{
"StatusCode": 200,
"ExecutedVersion": "$LATEST"
}
{"decision": "allow", "argv": ["ping", "-c", "3", "demo.example.internal"], "target": "demo.example.internal", "tool": "ping"}


The other three print the same  StatusCode  block, then:

=== 2. unknown target -> should DENY ===
{"decision": "deny", "reason": "unknown-host.evil.example is not in the authorized scope table"}

=== 3. explicitly unauthorized target -> should DENY ===
{"decision": "deny", "reason": "off-limits.example.internal is recorded but explicitly NOT authorized"}

=== 4. disallowed tool name -> should DENY ===
{"decision": "deny", "reason": "unknown tool: rm -rf /"}



  • Test 1 is the only request that returns a command.
  • Test 2 is the failure from the intro. A host nobody approved is refused.
  • Test 3 shows why the table stores an authorized flag. The gate can tell "we've never heard of this host" apart from "we looked at it and decided no."
  • Test 4 shows why callers send a tool name instead of a command. rm -rf / is never parsed or run. It isn't a key in the fixed map, so it's denied before the database is queried.
This proves the gate answers correctly. It doesn't yet prove anything stops a command from running. For that you need a caller.

With and without the gate

The repo includes run-with-gate.py. It builds no commands of its own. It sends the tool name and target to the gate and runs only the argument list that comes back. Two details matter:

if not isinstance(decision, dict) or decision.get("decision") != "allow":
print(f"BLOCKED: ..."); return 1 # anything but a clean allow runs nothing
...
return subprocess.run(argv).returncode # a list, so no shell ever parses it


If the gate is unreachable, returns bad JSON, or answers in the wrong shape, nothing runs. That's the same default-deny rule applied on the caller's side. Run it with no arguments to see how to use it:

./run-with-gate.py
Usage: ./run-with-gate.py [--dry-run] <tool> <target>
Example: ./run-with-gate.py ping 127.0.0.1
Runs the tool only if the safety gate allows it.


Without the gate, a script does ping -c 3 "$1". Given any hostname, it pings it. Nothing checks scope.
With the gate, try pinging your own machine. Nobody has approved it yet, so the gate refuses:

./run-with-gate.py ping 127.0.0.1
BLOCKED: 127.0.0.1 is not in the authorized scope table


Now approve it by adding one record to the table. The script doesn't change:

AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 \
aws --endpoint-url=http://localhost:4566 dynamodb put-item \
--table-name scope \
--item '{"target": {"S": "127.0.0.1"}, "authorized": {"BOOL": true}}'


Run the same command again:

./run-with-gate.py ping 127.0.0.1
ALLOWED: running ['ping', '-c', '3', '127.0.0.1']
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.081 ms
...
3 packets transmitted, 3 received, 0% packet loss


That is the pattern working: scope lives in one table, and changing one record changes what every script may do. (The credentials above are the dummy values LocalStack accepts. Real AWS would use your own.) The same refusal applies to a recorded-but-unauthorized host and to a tool name that isn't in the map. The script also resists injection. A target that tries to smuggle in a second command is just an unknown host:

./run-with-gate.py ping '127.0.0.1; echo PWNED'
BLOCKED: 127.0.0.1; echo PWNED is not in the authorized scope table


Add  --dry-run  to print the argument list without running it.

Troubleshooting

The container engine (Podman or Docker)

I ran this on Parrot OS with Podman, and  ./start-localstack.sh  failed before LocalStack started. The cause applies to anyone whose  docker  command isn't talking to a plain Docker daemon.

Symptom

failed to connect to the docker API at unix:///run/user/1000/podman/podman.sock


Cause. The  docker  command sends requests to whatever socket the  DOCKER_HOST  variable names. Mine pointed at Podman's socket, which is provided by a systemd service,  podman.socket . That service was disabled, so nothing was listening and the connection failed with "no such file or directory". The  chmod +x  step was not the problem. The script was already executable.

Check yours

echo $DOCKER_HOST
systemctl --user status podman.socket



Fix, choose one

  • Using Podman. Start the socket now and on every login:

systemctl --user enable --now podman.socket


  • Using Docker. Unset the variable so the CLI uses the real Docker daemon:

unset DOCKER_HOST


Your user must be in the docker group, or you'll get a permission error on  /var/run/docker.sock .
Why the script mounts a socket. LocalStack starts each Lambda in a separate container, so it needs to talk to your container engine. The script mounts your engine's socket into the LocalStack container to allow it. The original script always mounted  /var/run/docker.sock , which belongs to the real Docker daemon, so on Podman LocalStack couldn't start Lambda containers. The script now mounts whichever socket  DOCKER_HOST  names and falls back to  /var/run/docker.sock  when it's unset. That works for  unix://  sockets. If  DOCKER_HOST  is a  tcp://  address, unset it.
I tested the Podman path on Linux. I haven't tested Docker Desktop on macOS or Windows, where the socket location differs. If the Lambda won't start there, check where your engine's socket lives.

Errors you may see when running the scripts

I hit these while building this. None of them is a bug in the gate:

What you see
What it means
What to do
 start-localstack.sh  ends with "did not become healthy within 2 minutes"
LocalStack didn't start. Usually the container engine, see above
Check  docker logs localstack-demo 
 ResourceConflictException … state: Pending 
You invoked the Lambda before it finished starting
Wait for  Active , then retry
 ResourceNotFoundException: Function not found 
The Lambda doesn't exist. You ran  test.sh  before  deploy.sh , or you recreated the container
Run  ./deploy.sh 
 Table already exists: scope 
You ran  deploy.sh  twice against the same container
Clean up and start fresh (next section)
 gate unreachable from run-with-gate.py 
LocalStack isn't running, or you restarted the container and lost the deployment
Run  ./start-localstack.sh  and  ./deploy.sh 

The  Function not found  error is worth understanding. Here, everything lives inside the container. If you stop or recreate it, the table, the role, and the Lambda are gone, and you have to run  deploy.sh  again.

Clean up

 deploy.sh  can't run twice against the same container. To redeploy or finish, clean up:

./cleanup.sh


This force-removes the  localstack-demo  container, which deletes the table, role, and Lambda with it. It also deletes  out1.json  to  out4.json  and  gate_lambda.zip . It prints:

localstack-demo
cleaned up.


The LocalStack image stays on disk, so the next start is fast. To redeploy, run  ./start-localstack.sh  and  ./deploy.sh  again.

What this does not protect against

Read this before you use the pattern for anything real.
  • A script can skip the gate. run-with-gate.py  obeys the gate because it was written to. Nothing forces any other script to. Anyone can still type  ping  directly. The gate protects against mistakes and drift, not against someone who bypasses it. To enforce it, make one runner (a container or host) the only place tools can execute, and let it start them only from a gate-issued argument list. That's a change to your environment, not something this demo does.
  • Targets can look like options. A target of  -f  or  --help  could be read by the tool as a flag. Validate the target format (hostname or IP) in the gate, and put -- before the target where the tool supports it. The demo doesn't do this.
  • The table is only as trustworthy as who can write to it. Anyone who can write to the DynamoDB table can authorize anything. Restrict write access with IAM, and restrict who can invoke the Lambda too.
  • Records don't say who approved them. For an audit trail, store the approver and a timestamp in each record.

What you now have

You built a gate that denies by default, accepts only fixed tool names, and returns an argument list instead of a shell string. You wrote a caller that runs a command only when the gate allows it, and you saw the same script refuse  ping 127.0.0.1  until you added one record, then run it. To adopt the pattern, put your own tool names in  ALLOWED_TOOLS,  add your approved targets to the table, and change your scripts to run only what the gate returns.
The biggest problems I hit weren't in the gate logic. They were the container engine setup and waiting for the Lambda to finish starting, and both are covered above.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article