forked from Agilicus/endoscope
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scope
executable file
·376 lines (345 loc) · 16.2 KB
/
scope
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
#!/usr/bin/env python3
# pip install -r requirements.txt
#
# We have a new container with some tools (ping et al)
# We run it as a privileged Pod, mounting CRI + netns.
# Inside it we find the pid of the 'source', and from
# this we can do a 'nsenter -n -t <pid>', putting us
# in the same network namespace.
#
# Now we can 'tcpdump to stdout'
#
# See extcap for how to integrate with wireshark.
# e.g. /usr/lib/x86_64-linux-gnu/wireshark/extcap/sshdump
import argparse
import logging
import yaml
import re
import os
import sys
import json
import time
from kubernetes import client, config
from kubernetes.stream import stream
from kubernetes.stream.ws_client import ERROR_CHANNEL
if os.path.basename(sys.argv[0]) == 'k8scap':
sys.argv.insert(1, '--pod')
sys.argv.insert(2, 'None')
sys.argv.insert(3, 'dumpcap')
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--debug', help='Debug API stream', default = False, action = 'store_true')
parser.add_argument('-i', '--image', help='Image to scope with', default = 'agilicus/endoscope')
parser.add_argument('-n', '--namespace', help='Source namespace', default = 'default')
parser.add_argument('-p', '--pod', help='Source pod', default = '', required = True)
parser.add_argument('-c', '--regcred', help='Registry credentials, if private', default = '')
parser.add_argument('-t', '--terminate', help='Terminate (do not cache) debug pod (e.g. terminate each time)', action = 'store_true', default = False)
subparsers = parser.add_subparsers(help='command',dest='command')
## Ping
parser_ping = subparsers.add_parser('ping', help='ping help')
parser_ping.add_argument('-d', '--dest-pod', help='Destination pod')
parser_ping.add_argument('-N', '--dest-namespace', help='Destination pod namespace', default = 'default')
parser_ping.add_argument('-c', '--count', help='Count of pings to send', default = '1')
parser_ping.add_argument('-C', '--loopcount', help='Count of pings to send before new flow/ICMP ID', default = '5')
parser_ping.add_argument('-i', '--interval', help='Interval of pings to send', default = '0.1')
parser_ping.add_argument('-g', '--graph', help='Graph result', action = 'store_true', default = False)
parser_ping.add_argument('-a', '--all', help='Ping all in namespace (pod ip)', action = 'store_true', default = False)
parser_ping.add_argument('-H', '--host', help='Ping all in namespace (host ip)', action = 'store_true', default = False)
## Shell
parser_shell = subparsers.add_parser('shell', help='shell help')
parser_shell.add_argument('args', nargs=argparse.REMAINDER)
## Launch
parser_launch = subparsers.add_parser('launch', help='launch help')
## Cleanup
parser_cleanup = subparsers.add_parser('cleanup', help='cleanup. If source-pod == all, delete all debug- in namespace.')
## pids
parser_pids = subparsers.add_parser('pids', help='Show pids in namespace')
## strace
parser_strace = subparsers.add_parser('strace', help='Show syscalls of pid in pod')
parser_strace.add_argument('-p', '--pid', help='Override first pid (see pids commmand)', default = '')
parser_strace.add_argument('-e', '--expr', help='Set the strace filter (-e) expression, e.g. -e file', default = '')
## gdb
parser_gdb = subparsers.add_parser('gdb', help='Attach gdb to pid')
parser_gdb.add_argument('-p', '--pid', help='Override first pid (see pids commmand)', default = '')
## hping
parser_hping = subparsers.add_parser('hping', help='hping help')
parser_hping.add_argument('-d', '--dest-pod', help='Destination pod')
parser_hping.add_argument('-N', '--dest-namespace', help='Destination pod namespace', default = 'default')
parser_hping.add_argument('args', nargs=argparse.REMAINDER)
## dumpcap
parser_hping = subparsers.add_parser('dumpcap', help='dumpcap help')
parser_hping.add_argument('--extcap-interfaces', help='extcap interfaces', action = 'store_true')
parser_hping.add_argument('--extcap-interface', help='extcap interface')
parser_hping.add_argument('--extcap-capture-filter', help='extcap-capture-filter')
parser_hping.add_argument('--extcap-dlts-interface', help='extcap dlts', action = 'store_true')
parser_hping.add_argument('--extcap-config', help='extcap-config', action = 'store_true')
parser_hping.add_argument('--capture-config', help='config', action = 'store_true')
parser_hping.add_argument('--capture', help='capture', action = 'store_true')
parser_hping.add_argument('--filter', help='filter', default='')
parser_hping.add_argument('--fifo', help='fifo')
parser_hping.add_argument('args', nargs=argparse.REMAINDER)
args = parser.parse_args()
template = """
apiVersion: v1
metadata:
name: {name}
spec:
nodeName: {node_name}
hostPID: true
restartPolicy: Never
{imagePullSecrets}
containers:
- name: {name}
imagePullPolicy: Always
securityContext:
privileged: true
capabilities:
add: ["SYS_PTRACE", "NET_ADMIN"]
image: {image}
volumeMounts:
- mountPath: /var/run/dockershim.sock
name: crisock
- mountPath: /run/docker/netns
name: netns
- mountPath: /var/lib/docker
name: dockerlib
env:
- name: "LINES"
value: "{lines}"
- name: "COLUMNS"
value: "{columns}"
- name: "TERM"
value: "{term}"
volumes:
- hostPath:
path: /var/run/dockershim.sock
type: ""
name: crisock
- hostPath:
path: /var/run/docker/netns
type: ""
name: netns
- hostPath:
path: /var/lib/docker
type: ""
name: dockerlib
"""
def findFirstPid(name, args, spod, api):
# This is a bit gross, I'm not sure a better way. We have the cgroup-name
# from 'container_statuses': [{'container_id': 'docker://5f5f3135d5ff2300ea478704a774ed758b5c476888ff881bfa178436693ea410'...]
# and, this is references in <hostpid>/cgroup. There could be more than 1 pid in that cgroup,
# but we just care about the first since we use it to enter the netns.
# So, we run grep -l CGROUP /proc/*/cgroup, and then split the result.
docker_name = spod.status.container_statuses[0].container_id
cgroup = re.sub("^docker://","", docker_name)
cmd = ['/bin/sh', '-c','/bin/grep -l pids:/.*%s /proc/*/cgroup' % cgroup]
line = stream(api.connect_get_namespaced_pod_exec, name=name, container=name, namespace=spod.metadata.namespace, command=cmd, stderr=True, stdin=False, stdout=True, tty=False)
_pids = list(filter(None, str.split(line, '\n')))
pidlist = []
for pid in _pids:
pid = re.sub("[^[0-9]*","", pid)
if pid != None:
pidlist.append(pid)
pidlist.sort(key=int)
return pidlist[0]
def runit(name, args, spod, cmd):
pid = findFirstPid(name, args, spod, api)
ns_command = ['/usr/bin/nsenter', '-n', '-t', pid] + cmd
resp = stream(api.connect_get_namespaced_pod_exec, container=name, name=name, namespace=spod.metadata.namespace, command=ns_command, stderr=True, stdin=False, stdout=True, tty=False, _preload_content=False)
rc = -1
while resp.is_open():
resp.update(timeout=1)
if resp.peek_stdout():
print(resp.read_stdout(), end='')
if resp.peek_stderr():
print(resp.read_stderr(), file=sys.stderr, end='')
if resp.peek_channel(ERROR_CHANNEL):
status = json.loads(resp.read_channel(ERROR_CHANNEL))
if status['status'] == 'Success':
rc = 0
else:
rc = int(status['details']['causes'][0]['message'])
resp.close()
return rc
def launch(name, args, spod, api):
try:
columns, lines = os.get_terminal_size()
except:
# e.g. not a tty
columns = 80
lines = 24
imagePullSecrets = "imagePullSecrets:\n - name: %s" % args.regcred if len(args.regcred) else ""
ym = template.format(name=name, node_name=spod.spec.node_name, image=args.image, lines=lines, columns=columns, term=os.getenv('TERM'), imagePullSecrets=imagePullSecrets)
sm = yaml.load(ym)
try:
api.create_namespaced_pod(namespace=spod.metadata.namespace, body=sm)
while True:
resp = api.read_namespaced_pod(namespace=spod.metadata.namespace, name=name)
if resp.status.phase != 'Pending':
break
time.sleep(0.1)
except client.rest.ApiException as e:
if e.status == 409:
# Conflict, e.g. exists, we'll use it
pass
else:
raise e
return 0
def shell(name, args, spod, api):
launch(name, args, spod, api)
# As a special case, if args is empty, make an interactive shell
# if we are a tty
if len(args.args) == 0 and os.isatty(0):
pid = findFirstPid(name, args, spod, api)
rc = os.system("kubectl -n %s exec -it %s -- /usr/bin/nsenter -n -t %s bash" % (spod.metadata.namespace, name, pid))
rc = (rc & 0xff00) >> 8
else:
cmd = args.args
rc = runit(name, args, spod, cmd)
if args.terminate == True:
body = client.V1DeleteOptions()
api.delete_namespaced_pod(namespace=spod.metadata.namespace, name=name, body=body)
return rc
def ping(name, args, spod, api):
launch(name, args, spod, api)
ips = []
cmd = ['/usr/bin/noping' if args.graph else '/usr/bin/oping', '-c', args.count, '-C', args.loopcount, '-i', args.interval]
if args.all:
spods = api.list_namespaced_pod(watch=False, namespace=args.dest_namespace)
for _spod in spods.items:
cmd.append(_spod.status.pod_ip) if not args.host else cmd.append(_spod.status.host_ip)
else:
spods = api.list_namespaced_pod(watch=False, namespace=args.dest_namespace, field_selector='metadata.name=%s' % args.dest_pod )
for _spod in spods.items:
cmd.append(_spod.status.pod_ip)
rc = runit(name, args,spod,cmd)
if args.terminate == True:
body = client.V1DeleteOptions()
api.delete_namespaced_pod(namespace=spod.metadata.namespace, name=name, body=body)
return rc
def cleanup(name, args, spod, api):
if spod == None:
dpods = api.list_namespaced_pod(watch=False, namespace=args.namespace).items
else:
dpods = api.list_namespaced_pod(watch=False, namespace=args.namespace, field_selector = 'metadata.name=debug-%s' % spod.metadata.name).items
for pod in dpods:
body = client.V1DeleteOptions()
if re.match("^debug-", pod.metadata.name):
print("Delete %s/%s" % (pod.metadata.namespace, pod.metadata.name))
api.delete_namespaced_pod(namespace=pod.metadata.namespace, name=pod.metadata.name, body=body)
return 0
def pids(name, args, spod, api):
launch(name, args, spod, api)
docker_name = spod.status.container_statuses[0].container_id
cgroup = re.sub("^docker://","", docker_name)
cmd = ['/bin/sh', '-c','/bin/grep pids:/.*%s /proc/*/cgroup' % cgroup]
line = stream(api.connect_get_namespaced_pod_exec, container=name, name=name, namespace=spod.metadata.namespace, command=cmd, stderr=True, stdin=False, stdout=True, tty=False)
_pids = list(filter(None, str.split(line, '\n')))
pids = []
for pid in _pids:
pid = re.sub("/cgroup.*","", pid)
pid = re.sub("[^[0-9]*","", pid)
pids.append(pid)
print(' '.join(pids))
return 0
def strace(name, args, spod, api):
launch(name, args, spod, api)
if len(args.pid) == 0:
args.pid = findFirstPid(name, args, spod, api)
cmd = ['/usr/bin/strace', '-p', args.pid]
if len(args.expr):
cmd.append ( '-e' )
cmd.append ( args.expr )
return runit(name, args, spod, cmd)
def gdb(name, args, spod, api):
launch(name, args, spod, api)
if len(args.pid) == 0:
args.pid = findFirstPid(name, args, spod, api)
return os.system("kubectl -n %s exec -it %s -- /usr/bin/nsenter -p -t %s /usr/bin/gdb -p %s" % (spod.metadata.namespace, name, args.pid, args.pid))
def hping(name, args, spod, api):
launch(name, args, spod, api)
if len(args.args) and args.args[0] == '--':
args.args = args.args[1:]
cmd = ['/usr/sbin/hping3'] + args.args
spods = api.list_namespaced_pod(watch=False, namespace=args.dest_namespace, field_selector='metadata.name=%s' % args.dest_pod )
for _spod in spods.items:
cmd.append(_spod.status.pod_ip)
rc = runit(name, args,spod,cmd)
if args.terminate == True:
body = client.V1DeleteOptions()
api.delete_namespaced_pod(namespace=spod.metadata.namespace, name=name, body=body)
return rc
# 1. k8scap --extcap-interfaces
# 2. k8scap --extcap-config --extcap-interface k8scap
# 3. k8scap --extcap-dlts --extcap-interface k8scap
# 4. k8scap --extcap-config --extcap-interface k8scap
# 5. k8scap --capture --extcap-interface k8scap
# dumpcap -n -i /tmp/xxx -Z none
def dumpcap(name, args, spod, api):
#["python3", "/usr/lib/x86_64-linux-gnu/wireshark/extcap/k8scap", "--capture", "--extcap-interface", "default/ingress-nginx-ingress-controller-7b66cb4878-x7wwb", "--fifo", "/tmp/wireshark_extcap_default-ingress-nginx-ingress-controller-7b66cb4878-x7wwb_20180813162059_RCnP40"], 0x7ffd92b919e0 /* 59 vars */) = 0
if args.capture:
namespace = args.extcap_interface.split('/')[0]
pod = args.extcap_interface.split('/')[1]
spods = api.list_namespaced_pod(watch=False, namespace=namespace, field_selector='metadata.name=%s' % pod)
spod = spods.items[0]
name = 'debug-%s' % spod.metadata.name
launch(name, args, spod, api)
pid = findFirstPid(name, args, spod, api)
command = ['/bin/sh', '-c', '/usr/bin/nsenter -n -t %s /usr/local/bin/dumpcap -f \'%s\' -w - q 2>/dev/null' % (pid,args.filter)]
resp = stream(api.connect_get_namespaced_pod_exec, container=name, name=name, namespace=spod.metadata.namespace, command=command, stderr=True, stdin=False, stdout=True, tty=False, _preload_content=False)
fd = open(args.fifo, "wb")
while resp.is_open():
resp.update(timeout=10)
if resp.peek_stdout():
ln = resp.read_stdout()
fd.write(ln)
if resp.peek_stderr():
print(resp.read_stderr(), file=sys.stderr, end='')
if resp.peek_channel(ERROR_CHANNEL):
status = json.loads(resp.read_channel(ERROR_CHANNEL))
if status['status'] == 'Success':
rc = 0
else:
rc = int(status['details']['causes'][0]['message'])
fd.close()
resp.close()
elif args.extcap_config and len(args.extcap_interface):
print("arg {number=0}{call=--filter}{type=string}{default=''}{display=Capture filter}")
elif args.extcap_config:
print("arg {number=0}{call=--namespace}{display=namespace}{type=string}{tooltip='*|all|namespace'}")
print("arg {number=1}{call=--pod}{display=pod}{type=string}{default='*'}{tooltip='*|pod'}")
print("arg {number=2}{call=dumpcap}{display=dumpcap}")
print("arg {number=3}{call=--remote-filter}{display=remote filter}")
elif args.extcap_interfaces:
print("k8scap {version=0.1.0}{help=https://git.agilicus.com/utilities/endoscope}")
spods = api.list_pod_for_all_namespaces(watch=False)
for spod in spods.items:
print("interface {value=%s/%s}{display=Capture on ns:%s, pod:%s}" % (spod.metadata.namespace, spod.metadata.name, spod.metadata.namespace,spod.metadata.name))
#######
config.debug = True
config.load_kube_config()
api = client.CoreV1Api()
if args.debug:
import websocket
kslogger = logging.getLogger('kubernetes')
urllogger = logging.getLogger('urllib3')
clientlogger = logging.getLogger('client')
websocketlogger = logging.getLogger('websocket')
console_h= logging.StreamHandler()
kslogger.addHandler(console_h)
kslogger.setLevel(logging.DEBUG)
clientlogger.setLevel(logging.DEBUG)
websocketlogger.setLevel(logging.DEBUG)
websocket.enableTrace(True, console_h)
# Cleanup can accept 'all', which doesn't match
if args.command == 'dumpcap' or (args.command == 'cleanup' and args.pod == 'all'):
spod = None
name = None
else:
spods = api.list_namespaced_pod(watch=False, namespace=args.namespace, field_selector='metadata.name=%s' % args.pod)
if len(spods.items) == 0:
print("Error: %s/%s does not specify a valid pod" % (args.namespace, args.pod), file=sys.stderr)
sys.exit(1)
spod = spods.items[0]
name = 'debug-%s' % spod.metadata.name
r = locals()[args.command](name, args, spod, api)
sys.exit(r)