Skip to content
This repository was archived by the owner on Mar 1, 2023. It is now read-only.

Commit c3421cb

Browse files
committed
initial
0 parents  commit c3421cb

10 files changed

+232
-0
lines changed

Dockerfile

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
FROM ruby:2.7.2-alpine3.13
2+
3+
ARG K8S_VERSION=1.18.8
4+
ENV K8S_VERSION=${K8S_VERSION}
5+
6+
# Install tools and etcd and get the api-server binary
7+
RUN apk add --no-cache --update -X http://dl-cdn.alpinelinux.org/alpine/edge/testing \
8+
bash tar git curl jq etcd etcd-ctl etcd-openrc openrc less && \
9+
gem install pry && \
10+
curl -Lo kube-apiserver https://dl.k8s.io/release/v${K8S_VERSION}/bin/linux/amd64/kube-apiserver && \
11+
chmod +x ./kube-apiserver && \
12+
mv ./kube-apiserver /usr/local/bin && \
13+
rm -rf /tmp/* && \
14+
rm -rf /var/cache/apk/* && \
15+
rm -rf /var/tmp/*
16+
17+
# Copy in startup script, k8s token file for auth, and the auger binary
18+
ADD support/launch.sh /
19+
ADD support/tokens.txt /
20+
ADD support/load.rb /
21+
22+
# Make exec
23+
RUN chmod +x /launch.sh /load.rb
24+
# Necessary for the auger binary to run
25+
RUN mkdir /lib64 && ln -s /lib/libc.musl-x86_64.so.1 /lib64/ld-linux-x86-64.so.2
26+
27+
EXPOSE 31337
28+
CMD ["/bin/bash", "-c", "/launch.sh"]

LICENSE

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Copyright 2021 Darkbit.io
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4+
5+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6+
7+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Makefile

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
SHELL := /usr/bin/env bash
2+
3+
IMAGENAME=k8s-mirror
4+
IMAGEREPO=darkbitio/$(IMAGENAME)
5+
IMAGEPATH=$(IMAGEREPO):latest
6+
7+
NDEF = $(if $(value $(1)),,$(error $(1) not set))
8+
9+
DOCKERBUILD=docker build -t $(IMAGEREPO):latest .
10+
11+
COMMAND=docker run --rm -it -p31337:8080 -v "$(PWD)/data":/data
12+
13+
.PHONY: build run shell
14+
build:
15+
@echo "Building $(IMAGEREPO):latest"
16+
@$(DOCKERBUILD)
17+
18+
run:
19+
@echo "Running in $(IMAGEREPO):latest"
20+
@$(COMMAND) $(IMAGEPATH) || exit 0
21+
22+
shell:
23+
@echo "Running a shell inside the container"
24+
@$(COMMAND) $(IMAGEPATH) /bin/bash || exit 0

README.md

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# K8s-mirror
2+
3+
## Why?
4+
5+
To enable high-fidelity, offline review of Kubernetes clusters as a part of Darkbit's cloud and Kubernetes security [consulting services offerings](https://darkbit.io/services/), a simple script to export all K8s resources from a cluster was developed. A modified version of this script is included in this repository as `kube-exporter.sh`.
6+
7+
The original goal of this export format was to support ingestion by the [OpenCSPM](https://github.com/opencspm/opencspm) analysis platform. However, there are instances where analysis is best performed with a quick run of `kubectl`. Without having direct access to a client's cluster, a "mirror" cluster is needed.
8+
9+
## How?
10+
11+
* Clone the repository
12+
* Run `kube-exporter.sh` against the target cluster. It's output file should be named `<kubecontext_name>.json`.
13+
* Copy `<kubecontext_name>.json` to `data/import.json`
14+
* Modify the `Dockerfile` to use the correct `K8S_VERSION`
15+
* Run `make build` to build the docker container.
16+
* Run `make run` to launch the "mirror" cluster container. This container runs etcd, loads the data from `/data/import.json` into etcd, and then launches an _insecure_ API server. That is, it runs without TLS, listens on `localhost:31337` and requires a simple token for authentication as `cluster-admin`.
17+
* Run `export KUBECONFIG=kubeconfig.honk`
18+
* Run `kubectl get pods -A` to query for pods in the "mirror" cluster container.
19+
* When done, kill the container to clean up.
20+
21+
## Warning!
22+
23+
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

data/.gitkeep

Whitespace-only changes.

kube-exporter.sh

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#!/usr/bin/env bash
2+
3+
set -eo pipefail
4+
5+
command -v kubectl >/dev/null 2>&1 || { \
6+
echo >&2 "kubectl is needed, but it's not installed. Aborting."
7+
echo >&2 "Refer to: https://kubernetes.io/docs/tasks/tools/install-kubectl/"
8+
exit 1
9+
}
10+
command -v jq >/dev/null 2>&1 || { \
11+
echo >&2 "jq is needed, but it's not installed. Aborting."
12+
echo >&2 "Refer to: https://stedolan.github.io/jq/"
13+
exit 1
14+
}
15+
16+
# Exports all resources from a K8s cluster
17+
# while redacting secrets values and env vars
18+
# Uses the current context
19+
20+
CONTEXT="$(kubectl config current-context | sed -e 's/\//_/g' | sed -e 's/:/_/g')"
21+
OUTPUTFILE="${CONTEXT}.json"
22+
touch "${OUTPUTFILE}"
23+
cat /dev/null > "${OUTPUTFILE}"
24+
25+
# API Resources
26+
APIRESOURCES="$(kubectl api-resources -o name --verbs list | sort -u)"
27+
REDACTEDRESOURCES='^(secrets|managedcertificate.+)$'
28+
for res in $APIRESOURCES; do
29+
if [[ $res =~ $REDACTEDRESOURCES ]]; then
30+
# redact secrets data values
31+
kubectl get $res --all-namespaces --chunk-size=50 -ojson | jq -rc --arg CONTEXT "$CONTEXT" '.items[] | walk(if type=="object" and has("kubectl.kubernetes.io/last-applied-configuration") then ."kubectl.kubernetes.io/last-applied-configuration"="REDACTED" else . end) | walk(if type == "object" and has("data") then .data[] = "REDACTED" else . end) | {asset_type: ("k8s.io/"+ .kind), name: ("//"+ $CONTEXT + .metadata.selfLink), resource: {version: "v1", discovery_document_uri: "https://raw.githubusercontent.com/kubernetes/kubernetes/master/api/openapi-spec/swagger.json", data: .}}' >> "${OUTPUTFILE}"
32+
else
33+
# redact anywhere env vars have "value"
34+
kubectl get $res --all-namespaces --chunk-size=50 -ojson | jq -rc --arg CONTEXT "$CONTEXT" '.items[] | walk(if type=="object" and has("kubectl.kubernetes.io/last-applied-configuration") then ."kubectl.kubernetes.io/last-applied-configuration"="REDACTED" else . end) | walk(if type=="object" and has("env") and (.env|type=="array") then walk(if type=="object" and has("name") and has("value") then .value="REDACTED" else . end) else . end) | {asset_type: ("k8s.io/"+ .kind), name: ("//"+ $CONTEXT + .metadata.selfLink), resource: {version: "v1", discovery_document_uri: "https://raw.githubusercontent.com/kubernetes/kubernetes/master/api/openapi-spec/swagger.json", data: .}}' >> "${OUTPUTFILE}"
35+
fi
36+
done
37+
38+
# Server version
39+
kubectl version -o json | jq -r '.serverVersion'| jq -rc --arg CONTEXT "$CONTEXT" '{asset_type: ("k8s.io/Version"), name: ("//"+ $CONTEXT + .metadata.selfLink), resource: {version: "v1", discovery_document_uri: "https://raw.githubusercontent.com/kubernetes/kubernetes/master/api/openapi-spec/swagger.json", data: .}}' >> "${OUTPUTFILE}"

kubeconfig.honk

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
apiVersion: v1
2+
kind: Config
3+
current-context: mirror
4+
clusters:
5+
- cluster:
6+
server: http://localhost:31337
7+
name: mirror
8+
users:
9+
- name: honk
10+
user:
11+
token: honk
12+
contexts:
13+
- context:
14+
cluster: mirror
15+
user: honk
16+
name: mirror

support/launch.sh

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#!/bin/bash
2+
3+
rc-status
4+
touch /run/openrc/softlevel
5+
rc-service etcd start
6+
/load.rb /data/import.json
7+
kube-apiserver --etcd-servers http://127.0.0.1:2379 --insecure-bind-address=0.0.0.0 --insecure-port=8080 --allow-privileged=true --authorization-mode=Node,RBAC --anonymous-auth=false --token-auth-file=/tokens.txt -v=0 --storage-media-type=application/json

support/load.rb

+87
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
#!/usr/bin/env ruby
2+
3+
require 'json'
4+
require 'yaml'
5+
require 'pry'
6+
7+
def run_insert(input, insert_path)
8+
result = IO.popen("etcdctl put #{insert_path}", 'r+') do |io|
9+
io.write(input)
10+
io.close_write
11+
io.read
12+
end
13+
result
14+
end
15+
16+
def parse_line(line)
17+
json = JSON.parse(line)
18+
namespace_name = json.dig('resource','data','metadata','namespace') || "unknown"
19+
resource_name = json.dig('resource','data','metadata','name') || "unknown"
20+
resource = json.dig('resource','data').to_json
21+
22+
case json.dig('asset_type')
23+
when "k8s.io/Node"
24+
run_insert(resource, "/registry/minions/#{resource_name}")
25+
when "k8s.io/Pod"
26+
run_insert(resource, "/registry/pods/#{namespace_name}/#{resource_name}")
27+
when "k8s.io/ComponentStatus"
28+
run_insert(resource, "/registry/componentstatuses/#{resource_name}")
29+
when "k8s.io/CSINode"
30+
run_insert(resource, "/registry/csinodes/#{resource_name}")
31+
when "k8s.io/ClusterRoleBinding"
32+
run_insert(resource, "/registry/clusterrolebindings/#{resource_name}")
33+
when "k8s.io/ClusterRole"
34+
run_insert(resource, "/registry/clusterroles/#{resource_name}")
35+
when "k8s.io/RoleBinding"
36+
run_insert(resource, "/registry/rolebindings/#{namespace_name}/#{resource_name}")
37+
when "k8s.io/Role"
38+
run_insert(resource, "/registry/roles/#{namespace_name}/#{resource_name}")
39+
when "k8s.io/Secret"
40+
run_insert(resource, "/registry/secrets/#{namespace_name}/#{resource_name}")
41+
when "k8s.io/ServiceAccount"
42+
run_insert(resource, "/registry/serviceaccounts/#{namespace_name}/#{resource_name}")
43+
when "k8s.io/Service"
44+
run_insert(resource, "/registry/services/specs/#{namespace_name}/#{resource_name}")
45+
when "k8s.io/Endpoints"
46+
run_insert(resource, "/registry/services/endpoints/#{namespace_name}/#{resource_name}")
47+
when "k8s.io/Event"
48+
run_insert(resource, "/registry/events/#{namespace_name}/#{resource_name}")
49+
when "k8s.io/ConfigMap"
50+
run_insert(resource, "/registry/configmaps/#{namespace_name}/#{resource_name}")
51+
when "k8s.io/EndpointSlice"
52+
run_insert(resource, "/registry/endpointslices/#{namespace_name}/#{resource_name}")
53+
when "k8s.io/Namespace"
54+
run_insert(resource, "/registry/namespaces/#{resource_name}")
55+
when "k8s.io/StorageClass"
56+
run_insert(resource, "/registry/storageclasses/#{resource_name}")
57+
when "k8s.io/APIService"
58+
run_insert(resource, "/registry/apiregistration.k8s.io/apiservices/#{resource_name}")
59+
when "k8s.io/PriorityClass"
60+
run_insert(resource, "/registry/priorityclasses/#{resource_name}")
61+
when "k8s.io/Lease"
62+
run_insert(resource, "/registry/masterleases/#{resource_name}")
63+
when "k8s.io/Version"
64+
# skip
65+
else
66+
puts "Skipping: #{line.to_s[0, 50]}"
67+
end
68+
end
69+
70+
def parse_input_file(file)
71+
IO.foreach(file) do |line|
72+
if JSON.parse(line)
73+
parse_line(line)
74+
else
75+
puts "ERROR parsing: #{line.to_s}"
76+
puts "EXITING"
77+
exit 1
78+
end
79+
end
80+
end
81+
82+
if ARGV.empty?
83+
puts "No input file passed as first argument. Exiting."
84+
exit 1
85+
else
86+
parse_input_file(ARGV[0])
87+
end

support/tokens.txt

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
honk,honk,honk,system:masters

0 commit comments

Comments
 (0)