CKS killer - Question 12 Hack Secrets

Question 12 | Hack Secrets - part 3

How to build the environment in home lab and mimic below results?

/ # curl https://kubernetes.default/api/v1/namespaces/restricted/secrets -H "Authorization: Bearer $(cat /run/secrets/kubernetes.io/serviceaccount/token)" -k
...
    {
      "metadata": {
        "name": "secret3",
        "namespace": "restricted",
...
          }
        ]
      },
      "data": {
        "password": "cEVuRXRSYVRpT24tdEVzVGVSCg=="
      },
      "type": "Opaque"
    }

This is how I attempted with failures:

sa.yaml
-------------------------------------------------
apiVersion: v1
kind: ServiceAccount
metadata:
  name:  backend-sa
automountServiceAccountToken: true

sa-pod.yaml
------------------------------------------------
apiVersion: v1
kind: Pod
metadata:
  name: backend
spec:
  serviceAccountName:  backend-sa
  containers:
  - image: nginx:1.9
    imagePullPolicy: IfNotPresent
    name: backend

verification
-------------------------------------------------
candidate@node01:~$ kubectl exec secret -- curl -k https://kubernetes.default/api/v1/namespaces/default/secrets -H "Authorization:Bearer {cat /run/secrets/kubernetes.io/serviceaccount/token}"
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   157  100   157    0     0   4575      0{--:--:-- --:--:-- --:--:--     0
  "kind": "Status",
  "apiVersion": "v1",
  "metadata": {},
  "status": "Failure",
  "message": "Unauthorized",
  "reason": "Unauthorized",
  "code": 401
} --:--:-- --:--:-- --:--:--  4757

I think it should be

-H "Authorization:Bearer $(cat /run/secrets/kubernetes.io/serviceaccount/token)"

thanks for pointing out this mistake

Can someone pls help? How to build the environment like this?

/ # curl https://kubernetes.default/api/v1/namespaces/restricted/secrets -H “Authorization: Bearer $(cat /run/secrets/kubernetes.io/serviceaccount/token)” -k

{
“metadata”: {
“name”: “secret3”,
“namespace”: “restricted”,

}
]
},
“data”: {
“password”: “cEVuRXRSYVRpT24tdEVzVGVSCg==”
},
“type”: “Opaque”
}

I would typically run curl from outside the cluster, but where kubectl will run. First, read this section of the docs, which shows how to get the needed token data out of K8s and into your shell:

# Get the token value
TOKEN=$(kubectl get secret default-token -o jsonpath='{.data.token}' | base64 --decode)

# Explore the API with TOKEN
curl -X GET $APISERVER/api --header "Authorization: Bearer $TOKEN" --insecure

This isn’t quite what you want; you want to get the token as mounted from the pod, so:

TOKEN=$(kubectl exec POD -- cat /var/run/secrets/kubernetes.io/serviceaccount/token)

This will let you work from your host system, rather than being limited to what utilities are available in the pod.