K8s API Auth and Grant

I wanted to access and control the Kubernetes API using certificates. I looked around online but did not find a single good write-up, so I collected a few articles and put them together. It is a bit messy, but the general idea is clear. Feel free to take what is useful.

API Server

kube-apiserver is one of the most important core components of Kubernetes. Its main responsibilities are:

  • Providing the REST API for cluster management, including authentication, authorization, data validation, and cluster state changes
  • Acting as the hub for data exchange and communication between other modules (other modules query or modify data through the API Server; only the API Server directly operates on etcd)

REST API

kube-apiserver can serve both HTTPS (listening on port 6443 by default) and HTTP (listening on 127.0.0.1:8080 by default). The HTTP API is insecure and performs no authentication or authorization; do not enable it in production. Both endpoints expose the same REST API format. See the Kubernetes API Reference for the call format of every API.

Local port

  • Receives HTTP requests
  • Defaults to 8080; change it with the API Server’s --insecure-port startup flag
  • Defaults to the localhost IP; change it with the --insecure-bind-address startup flag
  • Unauthenticated and unauthorized HTTP requests reach the API Server through this port

Secure port

  • Defaults to 6443; change it with the --secure-port startup flag
  • The default IP is a non-local host network address; set it with the --bind-address startup flag
  • Receives HTTPS requests
  • Used for authentication based on token files, client certificates, and HTTP Basic auth
  • Used for policy-based authorization
  • HTTPS access control is not enabled by default

Open a local unauthenticated debug port:

1
kubectl proxy --port=8080 &

Examples:

1
2
3
4
5
6
7
8
9
curl localhost:8080/api
curl localhost:8080/api/v1/pods
curl localhost:8080/api/v1/nodes/
curl localhost:8080/api/v1/services
curl localhost:8080/api/v1/replicationcontrollers

curl localhost:8080/api/v1/proxy/namespaces/kube-system/pods/coredns-565d847f94-fhmwh

curl localhost:8080/api/v1/proxy/namespaces/{namespace}/pods/{name}

The REST path for Node-related endpoints is /api/v1/proxy/nodes/{name}, where {name} is the node name or IP address.

1
2
3
/api/v1/proxy/nodes/{name}/pods/    # List information about all Pods on the specified node
/api/v1/proxy/nodes/{name}/stats/   # List statistics about physical resources on the specified node
/api/v1/prxoy/nodes/{name}/spec/    # List summary information about the specified node

The Pod information obtained here comes from the Node rather than the etcd database, so the two may differ in time. If you start the kubelet process with --enable-debugging-handles=true, the Kubernetes Proxy API also exposes:

1
2
3
4
5
6
7
/api/v1/proxy/nodes/{name}/run      # Run a container on the node
/api/v1/proxy/nodes/{name}/exec     # Run a command in a container on the node
/api/v1/proxy/nodes/{name}/attach   # Attach to a container on the node
/api/v1/proxy/nodes/{name}/portForward   # Forward ports for Pods on the node
/api/v1/proxy/nodes/{name}/logs     # List various logs for the node
/api/v1/proxy/nodes/{name}/metrics  # List metrics related to the node
/api/v1/proxy/nodes/{name}/runningpods  # List running Pods on the node
1
2
/api/v1/proxy/namespaces/{namespace}/pods/{name}/{path:*}      # Access a service endpoint of a pod
/api/v1/proxy/namespaces/{namespace}/pods/{name}               # Access a Pod

Use kubectl api-versions and kubectl api-resources to query the API versions and resource objects supported by the Kubernetes API.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
kubectl get nodes -o yaml

kubectl describe nodes  silas-thinkpad-l460 -o yaml

# Describe a node
kubectl describe nodes kubernetes-node-emt8.c.myproject.internal

# Describe a pod
kubectl describe pods/nginx

kubectl get pods -n <namespace> <pod-name>

## out pod info to yaml
kubectl get pods -n kube-system coredns-565d847f94-fhmwh -o yaml

hostIP is the Pod machine’s IP.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
spec:
  nodeName: silas-thinkpad-l460
status:
  containerStatuses:
  - containerID: containerd://aa0fa0870010a7758eb41b4b47b9e7251e500a905812c72259ca232ec2737ba0
    image: registry.k8s.io/coredns/coredns:v1.9.3
  hostIP: 192.168.255.6
  phase: Running
  podIP: 10.88.0.7
  podIPs:
  - ip: 10.88.0.7
  - ip: 2001:4860:4860::7

How to get the Kubernetes API host and port

Open a local unauthenticated debug port:

1
kubectl proxy --port=8080 &
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$ kubectl cluster-info
Kubernetes control plane is running at https://192.168.58.2:8443

kubectl config view

curl --cacert /etc/kubernetes/pki/ca.crt $KUBE_API/version

# Get pod info by http curl token

$ JWT_TOKEN_DEFAULT_DEFAULT=$(kubectl create token default)

curl $KUBE_API/api/v1/namespaces/kube-system/pods/coredns-565d847f94-fhmwh \
  --cacert /etc/kubernetes/pki/ca.crt  \
  --header "Authorization: Bearer $JWT_TOKEN_DEFAULT_DEFAULT" \

# Get pod info by http curl ssl

curl $KUBE_API/api/v1/namespaces/kube-system/pods/coredns-565d847f94-fhmwh \
--cacert /etc/kubernetes/pki/ca.crt  \
--cert /etc/kubernetes/pki/apiserver-kubelet-client.crt \
--key /etc/kubernetes/pki/apiserver-kubelet-client.key

kubectl get --raw /api/v1/namespaces/kube-system/pods/coredns-565d847f94-fhmwh

Create an auth TLS secret

1
kubectl create secret tls tls-secret --cert=path/to/tls.cert --key=path/to/tls.key
1
2
3
$ kubectl create secret tls my-tls-secret \
--key ca.key \
--cert ca.crt

Check the signature

1
2
cat /etc/kubernetes/pki/ca.crt | openssl x509 -text
cat client.crt | openssl x509 -text

1. Generate the CA key and certificate

1
$ openssl req -x509 -sha256 -newkey rsa:4096 -keyout ca.key -out ca.crt -days 356 -nodes -subj '/CN=Fern Cert Authority'

2. Generate the server key and certificate, and sign them with the CA certificate

1
2
$ openssl req -new -newkey rsa:4096 -keyout server.key -out server.csr -nodes -subj '/CN=meow.com'
$ openssl x509 -req -sha256 -days 365 -in server.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out server.crt

3. Generate the client key and certificate, and sign them with the CA certificate

1
2
3
$ openssl req -new -newkey rsa:4096 -keyout client.key -out client.csr -nodes -subj '/CN=Tiabao'

$ openssl x509 -req -sha256 -days 365 -in client.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -set_serial 02 -out client.crt

4. Create the SSL secret

1
2
3
kubectl create secret tls tls-secret --cert=client.crt --key=client.key

kubectl get secrets

5. curl calling example

1
2
3
4
5
6
7
8
9
curl $KUBE_API/api/v1/nodes/ \
  --cacert /etc/kubernetes/pki/ca.crt  \
  --cert /home/silas/Documents/haiwen/k8s/cmworker/k8s_proxy/temp/client.crt \
  --key /home/silas/Documents/haiwen/k8s/cmworker/k8s_proxy/temp/client.key

curl $KUBE_API/api/v1/namespaces/kube-system/pods/coredns-565d847f94-fhmwh \
  --cacert /etc/kubernetes/pki/ca.crt  \
  --cert /home/silas/Documents/haiwen/k8s/cmworker/k8s_proxy/temp/client.crt \
  --key /home/silas/Documents/haiwen/k8s/cmworker/k8s_proxy/temp/client.key

Extra:

1
2
kubectl describe secrets/db-user-pass
kubectl describe secrets/tls-secret
1
2
kubectl get clusterrolebinding
kubectl get serviceaccount

Grant a ClusterRole to a user

1
kubectl get clusterrolebinding
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
cat << EOF | kubectl apply -f -
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: tian-admin-bind
subjects:
  - kind: User
    name: tian-admin
    apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: cluster-admin
  apiGroup: rbac.authorization.k8s.io
EOF
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
cat << EOF | kubectl delete -f -
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: tian-admin-bind
subjects:
  - kind: User
    name: tian-admin
    apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: cluster-admin
  apiGroup: rbac.authorization.k8s.io
EOF

For a typical application, the user provides a username and password, the server checks the database to see whether they exist and are valid, and authentication succeeds or fails accordingly.

How does Kubernetes do it?

Although ordinary users cannot be created through API calls, Kubernetes cleverly authenticates users via certificates. In other words, any user who can present a valid certificate is authenticated by Kubernetes.

After authentication, Kubernetes treats the certificate’s CN as the username (for example, /CN=joker means the username is Joker) and the Organization as the user’s group. A Role bound to that username and group then determines the user’s permissions.

CC BY-NC-ND 4.0