Tag, You’re It: Label-based Firewall Rules for VCF Workloads

NSX firewall rules table: drop web-to-web, allow web-to-app, allow app-to-db on PostgreSQL, allow Avi to web, default deny NSX firewall rules table: drop web-to-web, allow web-to-app, allow app-to-db on PostgreSQL, allow Avi to web, default deny

In my posts on integrating Antrea-enabled VKS clusters with NSX and on wiring up VKS 3.6.0 with AddonConfig, I kept promising firewall rules driven by Kubernetes labels. Consider this the first payment on that promise.

To keep it simple, we start one step earlier. On a Supervisor with VPC networking, labels on vSphere Pods and VM Service VMs already show up in NSX as tags. There’s no VCF Automation and no Antrea involved, which makes it a great place to learn tag-based rules: label it, group it, lock it down.

In this post, I’ll deploy a three-tier demo, watch the labels become NSX tags, build tag-based VPC groups and one five-rule policy, and then prove it with a test matrix and hit counts. The long cloud-init and the full JSON live in the companion repo at nsx-tag-firewall-rules on GitHub, so this stays a quick hit.

What You’ll Need

  • VCF 9.1.1 – With vDefend Firewall licensed and a Supervisor using NSX VPC networking
  • A vSphere Namespace – Mine is shared with VKS cluster nodes, which matters later
  • An Ubuntu cloud image – Visible to that namespace through your content library
  • An NSX account – Local user with the Security Engineer role, plus the VCF CLI, kubectl and curl
  • Avi – Providing the LoadBalancer VIP for the web tier

Before You Apply: Create a VCF CLI Context

Before any YAML, point your tools at the Supervisor with a VCF CLI context. I use basic auth, which logs in with a vCenter SSO user, and the CLI asks for your credentials. Then list your contexts and switch to the namespace one:

vcf context create supervisor --endpoint https://<supervisor-ip> --insecure-skip-tls-verify --auth-type basic
vcf context list
vcf context use supervisor:<namespace>

Creating the context also adds a supervisor:<namespace> context for each vSphere Namespace you can access, and vcf context use makes it the default for kubectl. Everything after this runs in the right context, which is the best kind of context to be in. One caveat: –insecure-skip-tls-verify is for labs with self-signed certificates. In production, trust the vCenter root CA or replace the Supervisor certificate.

Step 1: Label the Workloads

With that context active, define all three tiers in one file. The labels are the whole trick: security.tier picks the tier and security.env marks it as dev. The web tier is two nginx pods behind a LoadBalancer Service:

apiVersion: apps/v1
kind: Deployment
metadata: {name: nginx, namespace: <namespace>}
spec:
  replicas: 2
  selector: {matchLabels: {app: nginx}}
  template:
    metadata:
      labels: {app: nginx, security.tier: web, security.env: dev}
    spec:
      containers:
      - name: nginx
        image: nginx:1.25-alpine
        ports: [{containerPort: 80}]
---
apiVersion: v1
kind: Service
metadata: {name: nginx, namespace: <namespace>}
spec:
  type: LoadBalancer
  selector: {app: nginx}
  ports: [{port: 80, targetPort: 80}]

The app and db tiers are VM Service VMs. Here’s demo-app. The demo-db VM is identical except for its name, app: demo-db, security.tier: db and a listener on 5432 instead of 8080:

apiVersion: vmoperator.vmware.com/v1alpha5
kind: VirtualMachine
metadata:
  name: demo-app
  namespace: <namespace>
  labels: {app: demo-app, security.tier: app, security.env: dev}
spec:
  className: best-effort-small
  imageName: vmi-xxxx            # an Ubuntu image from your content library
  storageClass: <storage-class>
  powerState: PoweredOn
  bootstrap:
    cloudInit:
      cloudConfig:
        write_files: []          # tiny listener on 8080 + systemd unit: see the companion repo
        runcmd: []               # opens 8080 in the guest firewall: see the companion repo

Apply the file and check what came up:

kubectl apply -f three-tier.yaml
kubectl -n <namespace> get deploy nginx
kubectl -n <namespace> get vm demo-app demo-db

One ordering note: demo-db has to be up before demo-app, because the app VM’s cloud-init writes the database address to /etc/tagdemo/db_host on first boot. Apply the nginx pieces and demo-db first, drop the db address into demo-app, then apply the rest. The companion repo’s README lists the exact run order.

The pods and Service were ready in under a minute. The VMs took about nine minutes the first time, while the Supervisor cached the image. My image also shipped with a default-drop host firewall, so the cloud-init opens 8080 and 5432 inside the guest. Without that, the tests time out even with no NSX rule in the way.

Step 2: See the Labels Become Tags

In NSX, the tags land on the VPC subnet port. First, set two shell variables, then list the ports on the pod subnet. The -k is only there because my lab manager has a self-signed certificate:

NSX=https://<nsx-manager>
V=/policy/api/v1/orgs/default/projects/default/vpcs/<vpc-id>
curl -k -u '<api-user>' "$NSX$V/subnets/<subnet-id>/ports"

Trimmed to the interesting tags, an nginx pod port carries:

app                  | nginx
security.tier        | web
security.env         | dev
pod-template-hash    | <hash>
nsx-op/namespace     | <namespace>        (plus other nsx-op/* system tags)

The rule is simple: the label key becomes the tag scope and the label value becomes the tag. There’s no dis:k8s: prefix, which is different from what Antrea discovers for pods on VKS clusters. The VM ports, demo-app-eth0 and demo-db-eth0, show the same pattern with security.tier set to app and db.

The key: the tags sit on the subnet port, not on the VM. NSX’s VM inventory shows tags: null for both VMs, so a group built on VM tags would be empty. We group on ports instead.

Step 3: Build Tag-Based Groups

Create one VPC group per tier. Each group has a single condition on the VpcSubnetPort member type, and the value is written as scope|tag. Here’s the web group, saved as tagdemo-web.json:

{
  "display_name": "tagdemo-web",
  "expression": [
    {"resource_type": "Condition", "member_type": "VpcSubnetPort", "key": "Tag",
     "operator": "EQUALS", "scope_operator": "EQUALS", "value": "security.tier|web"}
  ],
  "tags": [{"scope": "tagdemo", "tag": "3tier"}]
}

Send it with a PATCH, then repeat for tagdemo-app and tagdemo-db with security.tier|app and security.tier|db. Expect HTTP 200 and an empty body:

curl -k -u '<api-user>' -X PATCH "$NSX$V/groups/tagdemo-web" \
  -H 'Content-Type: application/json' -d @tagdemo-web.json

Membership took about 15 seconds to appear. Check it before writing any rules:

curl -k -u '<api-user>' "$NSX$V/groups/tagdemo-web/members/subnet-ports"
curl -k -u '<api-user>' "$NSX$V/groups/tagdemo-web/members/ip-addresses"

{ "results" : [ "<ip-web-1>", "<ip-web-2>" ], "result_count" : 2 }

I got exactly the two nginx pod ports, one VM port each in the app and db groups, and nothing from the VKS clusters sharing the VPC. Use members/subnet-ports and members/ip-addresses for VPC groups. The vpc-subnet-ports and segment-ports variants return HTTP 500 here.

Step 4: Write the Policy

Now the policy, tagdemo-3tier, with five rules. Its scope is only the three demo groups, so nothing else in the VPC is affected:

  • 10 – Drop web to web, any service
  • 20 – Allow web to app on TCP 8080
  • 30 – Allow app to db on TCP 5432
  • 35 – Allow the Avi service engines to web on TCP 80
  • 40 – Drop everything else, scoped to the three groups

Here’s the policy trimmed to its header and two rules. The rest are in the companion repo:

{
  "display_name": "tagdemo-3tier",
  "stateful": true,
  "logging_enabled": true,
  "sequence_number": 10,
  "scope": [
    ".../vpcs/<vpc-id>/groups/tagdemo-web",
    ".../vpcs/<vpc-id>/groups/tagdemo-app",
    ".../vpcs/<vpc-id>/groups/tagdemo-db"
  ],
  "rules": [
    {
      "id": "tagdemo-a-drop-web-web", "action": "DROP", "sequence_number": 10,
      "source_groups": [".../groups/tagdemo-web"],
      "destination_groups": [".../groups/tagdemo-web"],
      "scope": [".../groups/tagdemo-web"],
      "services": ["ANY"], "logged": true
    },
    {
      "id": "tagdemo-b-allow-web-app-8080", "action": "ALLOW", "sequence_number": 20,
      "source_groups": [".../groups/tagdemo-web"],
      "destination_groups": [".../groups/tagdemo-app"],
      "scope": [".../groups/tagdemo-web", ".../groups/tagdemo-app"],
      "services": ["/infra/services/Oracle_XMLDB_HTTP_port"], "logged": true
    }
  ]
}

Send the whole policy body in a single PATCH. Expect HTTP 200 and an empty body:

curl -k -u '<api-user>' -X PATCH "$NSX$V/security-policies/tagdemo-3tier" \
  -H 'Content-Type: application/json' -d @policy-3tier.json

Here’s a view of the policy from the NSX Manager UI:

NSX Manager E-W Firewall view of the tagdemo-3tier policy and its five rules NSX Manager E-W Firewall view of the tagdemo-3tier policy and its five rules

Can’t find it? VPC-scoped policies don’t show up under the global Security > Distributed Firewall view. Look under VPCs > Virtual Private Clouds, expand your VPC, then SECURITY > E-W Firewall Rules.

Step 5: Prove It

From inside one nginx pod, test each path. First, web to app on 8080, then app to db through the app VM’s /dbcheck page, which opens a TCP connection to the db on 5432:

kubectl -n <namespace> exec deploy/nginx -- wget -qO- -T4 http://<ip-app>:8080/
tagdemo-app ok

kubectl -n <namespace> exec deploy/nginx -- wget -qO- -T6 http://<ip-app>:8080/dbcheck
OK

Next, the paths that should fail, web to db and web to the other web pod. A drop rule is silent, so a blocked test shows up as a timeout rather than a refusal:

kubectl -n <namespace> exec deploy/nginx -- nc -zv -w3 <ip-db> 5432
nc: <ip-db> (<ip-db>:5432): Operation timed out

kubectl -n <namespace> exec deploy/nginx -- wget -qO- -T4 http://<ip-web-2>/
wget: download timed out

Here’s the full matrix. I also sent steady requests to both load balancer addresses throughout, and every one returned 200:

Test                      Expected   Actual
web -> app   tcp/8080     allowed    allowed
app -> db    tcp/5432     allowed    allowed
web -> db    tcp/5432     blocked    blocked
web -> web   tcp/80       blocked    blocked
web -> app/db tcp/22      blocked    blocked
Load balancer VIPs        200        200

Finally, read the rule hit counters, which come from the policy’s statistics endpoint:

curl -k -u '<api-user>' "$NSX$V/security-policies/tagdemo-3tier/statistics"

Rule   Action   Hits   Packets   Sessions
10     DROP       15        15          0
20     ALLOW       8        80          8
30     ALLOW       4        36          4
35     ALLOW    2287     37079       2279
40     DROP     2595      2604          3

Rule 10 shows 15 packets for about 27 blocked attempts, so don’t expect one hit per attempt. Rules 35 and 40 are noisy because they also count health checks, my probes, and DNS and NTP hitting the default deny.

Gotchas Worth Knowing

A few things bit me along the way:

  • Tags live on the subnet port – Not on the VM object, so group on VpcSubnetPort
  • Scope by tag, never by namespace or VPC – My namespace also holds VKS cluster nodes, and a namespace-wide rule would have hit them
  • Default deny needs a way in for the load balancer – Without rule 35, the Avi service engines couldn’t reach the pods, and 279 of 3,000 probe requests to the demo VIP failed for about 30 seconds. Rule 35 sources from the Avi-created group whose id ends in DataNics
  • VPC rules can’t use custom services – I tried global services, project services and inline service entries, and NSX rejected all three. Use the built-ins by path: PostgreSQL for 5432, and Oracle_XMLDB_HTTP_port for 8080, which is TCP 8080 despite the misleading name
  • Hit counters lag – Rule 10 read 0 for several minutes before its first hits appeared. Wait, then re-read

The biggest surprise was web to web, which stayed open even with rule 10 in place. A leftover global policy, legacy-k8s-policy, had one allow rule from legacy web group to itself, and that group matched the same security.tier|web tag. Global policies are evaluated before VPC policies, so the allow quietly won. List the leftovers before you start:

curl -k -u '<api-user>' "$NSX/policy/api/v1/infra/domains/default/security-policies"

I exported the policy to JSON as a backup, deleted it, and about a minute later rule 10 started blocking. If you reuse tag values, hunt for old rules that already speak the same language.

Looking Forward

We now have a working, tag-driven three-tier policy built by hand on a VPC. In the next post, Tags as code, I’ll rebuild the same groups and policy with the NSX Policy API and Terraform, so the whole thing is repeatable. After that, we’ll bring VKS clusters in with Antrea, and then mix VMs and pods under one policy. Stay tuned!

Leave a Reply