Skip to content
Back to skills

Secure Deployment

ASecurity

Use when deploying an application to a server or container host, hardening or auditing a Linux host, configuring TLS and ingress, the outbound mail stack, DNS records, or responding to a security incident on a running system. Carries the phase-ordered deploy workflow and the pre-deploy and post-deploy verification checks.

  • 2 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 5, 2026
ai-agentsgoshellbashnodedockerdebugginggitapidatabasesecurity

Works with

  • cli
  • api

Security analysis

A96/100
  • mediumUses curl or wget to download content

Pro scans all 5 files and shows the line behind each finding

Scanned December 5, 2026

npx -y skills add gethacked-ai/agent-security-skills --skill secure-deployment --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Secure Deployment?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Secure Deployment
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/gethacked-ai-secure-deployment/badge)](https://www.skillsdirectory.com/skills/gethacked-ai-secure-deployment)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: secure-deployment
description: >-
  Use when deploying an application to a server or container host, hardening or auditing a Linux host, configuring TLS and ingress, the outbound mail stack, DNS records, or responding to a security incident on a running system. Carries the phase-ordered deploy workflow and the pre-deploy and post-deploy verification checks.
metadata:
  version: "1.0"
---

# Secure deployment

## When to use

Use when:

- deploying an application to a server, VPS, or container host
- hardening or auditing a Linux host
- configuring an ingress reverse proxy, TLS certificates, or the outbound mail stack
- setting or verifying DNS records (A, MX, TXT, CNAME)
- responding to a security incident on a running system
- auditing drift on a host already in production

Do not use when:

- a routine code change carries no deployment, release, or infrastructure component
- the question is about one application's behaviour (framework, API, bug) and touches no server
- a single application question would otherwise pull in a full host audit — audit the application, not the host

## Two rules that never bend

**1. A file created over SSH is world-readable unless the mode is set in the same command.** SSH creates files with the login umask, typically 644. Set the mode at write time; correcting it afterwards leaves a window.

```
WRONG  cat .env | ssh deploy@host "cat > /srv/app/.env"
RIGHT  cat .env | ssh deploy@host "umask 077 && cat > /srv/app/.env"
```

Set the containing directory to 700 as well. Secrets must never transit through a location another account can read.

**2. Stop and ask.** Before any of these, stop and ask:

- a change to a shared resource's behaviour (an ingress vhost, a shared default site, a firewall rule, a service another application depends on)
- anything destructive to something you did not create (removing a configuration, deleting a volume, dropping a database)
- a restart or reconnect of a service carrying live traffic
- a DNS or provider-console change you cannot verify yourself

Surface the trade-off in two sentences, list the alternatives, let the operator choose. "Fix it" never means "do the aggressive thing".

## The deploy workflow

Run the phases in order. Each has an entry condition; do not start a phase before its entry condition is met.

| Phase | Entry condition |
|---|---|
| 0. Inventory the host | Always, before any change |
| 1. Build the artifact | Source builds and its checks pass |
| 2. Deploy user and directory | Host inventoried; account does not exist |
| 3. Transfer the artifact | Directory exists and is owned correctly |
| 4. Install config and secrets | Artifact extracted; no secret on disk yet |
| 5. Run under a supervisor | Config and secrets in place with correct mode |
| 6. Ingress and TLS | Process running and answering on loopback |
| 7. Mail and DNS | Domain confirmed to resolve to this host |
| 8. Verify | Every phase above complete |

**Why the order matters.** You cannot configure TLS for a virtual host you have not confirmed exists — a name collision silently routes another application's traffic to yours. You must not overwrite a co-tenant's vhost, so the inventory comes first. Secrets must never transit through a world-readable location, so the mode is set at write time rather than corrected afterwards. A certificate cannot be issued before DNS points at the host, so the domain is verified in Phase 0 and the records themselves are published by a human in Phase 7. Each phase's output is the next phase's input; skipping one leaves a gap that only shows up in production.

### Phase 0 — Inventory the host (read-only)

Entry: always, before touching anything.

```bash
ssh <user>@<host> "
  uname -a; cat /etc/os-release | head -3
  systemctl list-units --type=service --state=running --no-pager
  docker ps --format '{{.Names}}: {{.Ports}}'
  ls /etc/nginx/sites-enabled/; ss -tlnp; certbot certificates 2>/dev/null
  df -h / | tail -1; free -h | head -2
"
```

Treat every other application on the host as read-only. Do not chmod, chown, restart, or reconfigure anything the inventory found.

Never in this phase: install anything, change a service, or open a firewall port.

### Phase 1 — Build the artifact

Entry: source builds and its own checks pass.

```bash
tar --exclude='./node_modules' --exclude='./.git' --exclude='./.env*' --exclude='./.cache' \
    -czf /tmp/app-build.tar.gz -C <project-dir> .
```

Never in this phase: put a secret in the artifact, or unpack it on a shared host before the deployment user and directory exist.

### Phase 2 — Deploy user and directory

Entry: host inventoried; the deployment account does not yet exist.

```bash
useradd -r -s /bin/bash -d /srv <deploy-user> 2>/dev/null || true
mkdir -p /srv/<app>
chown -R <deploy-user>:<group> /srv/<app>
chmod 700 /srv/<app>
```

Give the account only what the application needs: no sudo, no interactive login for a service account.

Never in this phase: run the application as root, use mode 777, or reuse a directory that belongs to another application.

### Phase 3 — Transfer the artifact

Entry: Phase 2 complete.

```bash
scp -i <key> /tmp/app-build.tar.gz <user>@<host>:/tmp/
ssh <user>@<host> "tar -xzf /tmp/app-build.tar.gz -C /srv/<app> && chown -R <deploy-user>:<group> /srv/<app> && rm -f /tmp/app-build.tar.gz"
```

Never in this phase: transfer a secret file — secrets are configured on the host in Phase 4.

### Phase 4 — Install configuration and secrets

Entry: artifact extracted; no secret is on disk yet.

Write secrets directly on the host with the mode set in the same command, then re-assert it — extraction and copying reset modes:

```bash
ssh <user>@<host> "umask 077 && cat > /srv/<app>/.env"
chmod 600 /srv/<app>/.env
chmod 700 /srv/<app>
```

Never in this phase: create a secret file at 644 and fix it later, inline a secret into a compose `environment:` block, or print a secret value into a log, a command transcript, or a report.

### Phase 5 — Run under a supervisor

Entry: configuration and secrets in place with correct ownership and mode.

Use systemd, or a container runtime. The process runs as the deployment user, binds to loopback, and takes its environment from the secret file rather than from a shell.

Verify the environment reload semantics of your supervisor: many re-read the environment only on a fresh start, not on a restart, so a changed variable silently stays stale. If a changed variable has no effect after a restart, do a stop and a start.

Never in this phase: run the process as root, bind it to a public address, or let the application and the ingress both hold a public port.

### Phase 6 — Ingress and TLS

Entry: the process is running and answering on loopback; the domain is confirmed to resolve to this host.

One configuration file per domain, an explicit `server_name` on every block, a catch-all default server that refuses unknown hosts, TLS 1.2 or newer with a modern cipher set, HSTS, OCSP stapling where available, and no server version in the response headers. Run the configuration syntax test before every reload.

Never in this phase: run the certificate client without naming the domain — a bare invocation offers every name in the host's nginx configuration for selection onto one certificate, so it can cover the wrong hosts. Never overwrite another application's configuration, and never remove a shared default site without confirming what it serves.

Details and the external probe matrix: [references/nginx-tls.md](references/nginx-tls.md).

### Phase 7 — Outbound mail and DNS

Entry: the domain resolves to this host and the ingress serves it.

Configure the mail stack, sign outbound mail, publish the DNS records. SPF ends in a hard fail once the sending sources are known; DKIM signs with the correct selector and mode; DMARC starts in reporting-only mode with an aggregate reporting address, then stages the enforcement through `p` and `pct`; reverse DNS matches the sending hostname.

One address has one reverse-DNS record, so on a host running several applications, mail sending is a host-level decision, not a per-application one.

The DNS zone is usually managed in a different console from the server. The deliverable of this phase is a precise, verifiable list of the records a human must set — type, name, value, priority, TTL — with the command that confirms each one.

Details: [references/mail-and-dns.md](references/mail-and-dns.md).

### Phase 8 — Verify

Entry: all previous phases complete.

Run the post-deploy checks: the secret and permission sweep again, the port-exposure check again, the service and container inventory, certificate expiry, the ingress syntax test, and the external TLS probes. Every finding must flip to clean before the deploy is called done.

Details: [references/pre-deploy-checks.md](references/pre-deploy-checks.md).

## Pre-deploy checks

Run these before the deploy touches the host. Every command is expected to produce empty or correct output.

```bash
# World-readable secret files — must be empty
find /srv /opt -name '.env*' -not -name '*.example' -perm /o+r

# Likely keys in configuration files — must be empty
find /srv /opt \( -name '*.json' -o -name '*.yml' -o -name '*.yaml' \) \
  -exec grep -lE 'api[_-]?key|secret|token|BEGIN [A-Z ]*PRIVATE KEY' {} \; 2>/dev/null

# Wildcard-bound sockets — the ingress may hold these; every application port must be loopback
ss -tlnp | grep -E '(0\.0\.0\.0|\[::\]|\*):[^ *]'

# Running services and containers
systemctl list-units --type=service --state=running --no-pager
docker ps --format '{{.Names}}: {{.Status}}: {{.Ports}}'

# Certificate expiry
certbot certificates 2>/dev/null | grep -E 'Certificate Name|Expiry Date'

# Ingress configuration syntax — before any reload
nginx -t
```

Also confirm on the host before deploying: the application directory mode is 700 or 755 and never 777, the process does not run as root, and SSH denies root login with a password. The full audit harness, the code-level greps, and the fixes for common findings are in [references/pre-deploy-checks.md](references/pre-deploy-checks.md).

## Container hardening

Apply to every container in the deployment:

```yaml
services:
  app:
    image: <registry>/<image>:<version-tag>
    user: "<uid>:<gid>"
    read_only: true
    security_opt:
      - no-new-privileges:true
    cap_drop:
      - ALL
    cap_add:
      - NET_BIND_SERVICE
    mem_limit: 512m
    cpus: 1.0
    env_file:
      - .env
    ports:
      - "127.0.0.1:<host-port>:<container-port>"
```

- Run as a non-root user; `user:` overrides the image's own.
- Drop all capabilities and add back only the one the container actually needs.
- Set `no-new-privileges` so a process cannot gain privileges through a setuid binary.
- Set resource limits so one container cannot exhaust the host.
- Bind published ports to loopback and proxy through the ingress; never publish on a public address.
- Pin a specific image tag. A floating tag makes the running version unknown after a restart.
- Keep secrets in files referenced by `env_file`, never inline in the compose file.
- Keep both ignore files covering the secret files: the version-control ignore file (`.gitignore`) and the container build ignore file (`.dockerignore`) must exclude the secret file and its variants. A secret left in the version-control ignore file but not in the build ignore file ends up baked into an image layer.

## Ingress and TLS

- One server block per domain, in its own configuration file, with an explicit `server_name` on every block.
- A catch-all default server that refuses unknown hosts by closing the connection, so a request with a wrong or absent Host header never reaches an application.
- TLS 1.2 and 1.3 only, with a modern cipher set; HSTS with a long max-age.
- OCSP stapling on where the chain supports it.
- No server version in the response headers.
- Certificate renewal automated, and expiry monitored before it becomes an outage.
- Never run the certificate client without naming the domain.

Configuration, renewal, and the external probe matrix: [references/nginx-tls.md](references/nginx-tls.md).

## Mail and DNS

- SPF ends in a hard fail (`-all`), not a soft fail, once the sending sources are known. While unsure, keep the soft fail and run DMARC in reporting-only mode, then flip both.
- DKIM signs with OpenDKIM using the correct selector and mode `v` — sign only when the From domain matches. A mode that signs everything also signs forged mail.
- DMARC starts in reporting-only mode with a `rua` aggregate reporting address, then stages the enforcement: `p=quarantine; pct=10`, then `pct=100`, then `p=reject`. `pct` limits enforcement, not reporting — it never reduces the reports received, and it does nothing while `p=none`.
- Reverse DNS (PTR) matches the sending hostname. One address has one PTR, so on a shared host the sending hostname is a host-level decision.
- Record types: MX routes mail, TXT carries SPF, DKIM, DMARC and provider verification tokens, CNAME aliases one name to another.
- TTL governs propagation, not the provider's "saved" confirmation. Only a query against a public recursive resolver shows the record as the world sees it.
- The DNS zone is usually in a different console from the server. Produce the exact record list for the human, and confirm it with a resolver query after they set it.

Details: [references/mail-and-dns.md](references/mail-and-dns.md).

## Running more than one app on a host

- One ingress configuration, one compose project, and one network per application.
- Allocate a dedicated port per application and never reuse one. Confirm the port is free before writing the ingress block or the service definition.
- Unique container names across every project on the host; a name collision breaks the wrong application.
- Never remove or overwrite a shared default site. First find what is linked to it and confirm it serves nothing; then replace it with a catch-all rather than leaving the hole.
- Never run a compose teardown that deletes volumes without naming the exact project.

Debugging a cross-application problem:

```bash
nginx -T | grep server_name          # which block is the default, and what each claims
docker ps -a --format '{{.Names}}'   # duplicate names across projects
ss -tlnp                             # who holds the port
```

An application serving another application's certificate is almost always the default server block landing on the wrong vhost — check the effective configuration first.

## Drift and periodic audit

Re-run the audit quarterly even if nothing was deployed; drift is silent. Check accounts and sudo entries, the SSH configuration, the firewall, running services, the patch level, and the difference between the running state and the intended state.

What drifts without a deploy: pending package updates, DNS records changed elsewhere, expiring certificates, ban-list rules that no longer match the traffic, ports reopened by a package upgrade, and cloud-init re-applying a permissive sudo rule on an image rebuild.

## Incident response on a running system

1. Preserve evidence before remediating. Capture logs, process state, and the file inventory first; remediation destroys the evidence that identifies the scope.
2. A secret file that was world-readable at any point is a credential-compromise event. Rotate every credential in it — fixing the mode does not un-leak the keys, and deleting the file is not a rotation.
3. An exposed rate limiter or an authentication bypass is an incident, not a bug. Treat it with the same evidence-first discipline.
4. Identify the owner: which application, which account, which provider. An incident without an owner cannot be closed.
5. Never paste a secret value into a report. Report credential names, the exposure window, and revocation timestamps.

Procedure and rotation order: [references/incident-response.md](references/incident-response.md).

## Finish

A deploy is done only when all of the following have run and returned clean:

- the pre-deploy sweep, before the change
- the same sweep again, after the change
- the ingress syntax test before every reload
- the external TLS probes: protocol and cipher matrix, HSTS present, stapling, no version header, sensitive paths not served
- the service and container inventory showing the expected processes and nothing unexpected
- certificate expiry checked and renewal confirmed

Report as evidence: what changed, which checks ran and their result, what was deliberately not done and why, and any item that needs a human — a DNS record, a console change, a credential to rotate.

A deploy whose post-deploy checks have not passed is not done. Say so explicitly rather than reporting success.

## Example

Phase 6, one domain, on a host that already serves another application:

```bash
# Precondition: the inventory showed no block claiming this server_name.
cat > /etc/nginx/sites-available/<app> <<'NGINX'
server {
    listen 80;
    server_name <domain> www.<domain>;
    return 301 https://$host$request_uri;
}
NGINX
ln -sf /etc/nginx/sites-available/<app> /etc/nginx/sites-enabled/<app>
nginx -t                    # must pass before any reload: a bad block takes every app down
systemctl reload nginx

# Only after DNS resolves to this host:
certbot --nginx -d <domain> -d www.<domain> --non-interactive --agree-tos -m <email>

# Verify before calling the phase complete:
certbot certificates | grep -E 'Certificate Name|VALID:'
curl -sSI https://<domain>/ | grep -i strict-transport
```

Files in this skill

  • SKILL.md17.2 KB
  • references/incident-response.md5.4 KB
  • references/mail-and-dns.md10.8 KB
  • references/nginx-tls.md6.2 KB
  • references/pre-deploy-checks.md11.8 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.