/
secpod_wrap.py
executable file
·280 lines (235 loc) · 9.29 KB
/
secpod_wrap.py
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
#!/usr/bin/env python3
import sys
import datetime
import sqlite3
import argparse
import urllib3
import json
import os
import re
import uuid
import logging
import traceback
from shutil import which
from kubernetes import client, config
from kubernetes.stream import stream
sql_con = sqlite3.connect('example.db');
cur = sql_con.cursor();
aConfiguration = client.Configuration()
aToken = os.environ.get('K8S_TOKEN')
aConfiguration.host = os.environ.get('K8S_URL')
aConfiguration.verify_ssl = False
aConfiguration.api_key = {"authorization": "Bearer " + aToken}
aApiClient = client.ApiClient(aConfiguration)
v1_core = client.CoreV1Api(aApiClient)
v1_apps = client.AppsV1Api(aApiClient)
def resolveOwnerReference(pod) -> dict:
if pod.metadata.owner_references is None:
return {
"kind": "Pod",
"name": pod.metadata.name,
"namespace": pod.metadata.namespace,
"uid": pod.metadata.uid
}
else:
for res in pod.metadata.owner_references:
if res.kind == 'ReplicaSet':
replica_set = v1_apps.read_namespaced_replica_set(res.name, pod.metadata.namespace)
if not replica_set.metadata.owner_references is None:
rs_owner_reference = replica_set.metadata.owner_references[0]
kind = rs_owner_reference.kind
name = rs_owner_reference.name
uid = rs_owner_reference.uid
else:
kind = 'ReplicaSet'
name = res.name
uid = res.uid
elif res.kind == 'ReplicationController':
rep_controller = v1_core.read_namespaced_replication_controller(res.name, pod.spec.metadata.namespace)
if not rep_controller.metadata.owner_references is None:
rc_owner_reference = rep_controller.metadata.owner_references[0]
kind = rc_owner_reference.kind
name = rc_owner_reference.name
uid = rc_owner_reference.uid
else:
kind = 'ReplicationController'
name = res.name
uid = res.uid
else:
kind = res.kind
name = res.name
uid = res.uid
return {
"kind": kind,
"name": name,
"namespace": pod.metadata.namespace,
"uid": uid
}
def table_exists(name):
cur.execute(f"SELECT count(name) FROM sqlite_master WHERE type='table' AND name='{name}'")
if cur.fetchone()[0] == 1:
return True
else:
return False
def check_ns(ns):
try:
v1_core.read_namespace(name=ns)
except Exception as e:
print(f"{e}")
sys.exit(1)
def store(args):
if args.namespace:
check_ns(args.namespace)
if table_exists('images'):
print("Clean old records of images")
cur.execute("DROP TABLE images")
if table_exists('cve'):
print("Clean old records of cve")
cur.execute("DROP TABLE cve")
cur.execute('''CREATE TABLE images
(image text, container text, pod text, owner_name text, owner_kind text, namespace text, date date)''')
if not table_exists('cve'):
cur.execute('''CREATE TABLE cve
(image text, vuln_id text, installed_version text, primary_url text, severity text, date date)''')
if args.namespace:
ret = v1_core.list_namespaced_pod(watch=False, namespace=args.namespace)
else:
print(f"Looking for pods running on all namespaces")
ret = v1_core.list_pod_for_all_namespaces(watch=False)
if ret == [] and args.namespace:
print(f"Found 0 runnng pods. Dows namespace {args.namespace} exists?")
for i in ret.items:
pod = v1_core.read_namespaced_pod(name=i.metadata.name, namespace=i.metadata.namespace)
owner = resolveOwnerReference(pod)
owner_name = owner["name"]
owner_kind = owner["kind"]
for container in pod.spec.containers:
if not already_scanned(container.image):
scan(container.image)
date = datetime.datetime.now()
print(f"Save record for {container.image}")
query = f"""INSERT INTO images VALUES ('{container.image}',
'{container.name}',
'{i.metadata.name}',
'{owner_name}',
'{owner_kind}',
'{i.metadata.namespace}',
'{date}')"""
cur.execute(query)
sql_con.commit()
print("Images scanning completed")
def get_images(args):
if not table_exists("images"):
print(f"Please do: ./{sys.argv[0]} store")
sys.exit(1)
if args.namespace:
check_ns(args.namespace)
cur.execute(f"SELECT * FROM images WHERE namespace = '{args.namespace}'")
else:
cur.execute(f"SELECT * FROM images")
retval = []
rows = cur.fetchall()
if rows == []:
print(f"Query ha returned 0 elements. Please do \"{sys.argv[0]} store\"")
for row in rows:
retval.append({
"image": row[0],
"container": row[1],
"pod": row[2],
"owner": row[3],
"owen_kind": row[4],
"namespace": row[5]
})
print(json.dumps(retval, indent = 4))
def vulns(args):
cur.execute(f"SELECT * FROM cve")
stored_cve = cur.fetchall()
cve_list = {}
cve_list["cve"] = []
for cve in stored_cve:
cur.execute(f"SELECT * FROM images WHERE image = '{cve[0]}'")
related_images = cur.fetchall()
oweners = []
for r_img in related_images:
tmp_owner = { "owner": r_img[3], "owner_kind": r_img[4], "namespace": r_img[5] }
if not tmp_owner in oweners:
oweners.append(tmp_owner)
cve_dict = {
"image": cve[0],
"cve_id": cve[1],
"installed_version": cve[2],
"primary_url": cve[3],
"severity": cve[4],
"owners": oweners
}
cve_list["cve"].append(cve_dict)
print(json.dumps(cve_list, indent = 4))
def already_scanned(img):
cur.execute(f"SELECT * FROM cve WHERE image = '{img}'")
rows = cur.fetchall()
if rows != []:
print(f"Image {img} already checked")
return True
cur.execute(f"SELECT * FROM images WHERE image = '{img}'")
rows = cur.fetchall()
if rows != []:
print(f"Image {img} already checked")
return True
return False
def vuln_dict(vuls_dict_keys, vulns, key):
if key in vuls_dict_keys:
return vulns[key]
return "undefined"
def scan(img):
id = uuid.uuid1()
tmp_file = f"/tmp/trivy-{id.node}.json"
print(f'Scan {img}')
stream = os.popen(f'trivy -f json -o {tmp_file} {img}')
stream.read()
with open(tmp_file) as json_file:
data = json.load(json_file)
if "Results" in data:
data = data["Results"]
for results in data:
if "Vulnerabilities" in results:
for vulns in results["Vulnerabilities"]:
vulnid = vuln_dict(vulns.keys(), vulns, "VulnerabilityID")
inst_ver = vuln_dict(vulns.keys(), vulns, "InstalledVersion")
prim_url = vuln_dict(vulns.keys(), vulns, "PrimaryURL")
severity = vuln_dict(vulns.keys(), vulns, "Severity")
if severity in ["HIGH", "CRITICAL"]:
date = datetime.datetime.now()
query = f"SELECT * FROM cve WHERE vuln_id = '{vulnid}'"
cur.execute(query)
rows = cur.fetchall()
if rows == []:
query = f"INSERT INTO cve VALUES ('{img}', '{vulnid}', '{inst_ver}', '{prim_url}', '{severity}', '{date}')"
cur.execute(query)
sql_con.commit()
else:
print(f"{vulnid} already stored")
def tool_exists(name):
return which(name) is not None
if __name__ == '__main__':
if not tool_exists("trivy"):
print("trivy is not installed on this system, please install it")
sys.exit(1)
urllib3.disable_warnings()
parser = argparse.ArgumentParser(prog='secpod_wrap')
sub_parsers = parser.add_subparsers(help='sub-command help')
parser_store = sub_parsers.add_parser('store', help='Save pod and images in SQLite')
parser_store.set_defaults(func=store)
parser_store.add_argument('--namespace', type=str, help='Get images of a specific namespace', dest='namespace')
parser_store.add_argument('--all-namespaces', type=bool, help='Get images of all namespaces', dest='all_namespaces')
parser_images = sub_parsers.add_parser('images', help='Get images list')
parser_images.set_defaults(func=get_images)
parser_images.add_argument('--namespace', type=str, help='Get images of a specific namespace', dest='namespace')
parser_images.add_argument('--pod', type=str, help='Name of the pod', dest='pod')
parser_podvulns = sub_parsers.add_parser('vulns', help='Get images cve of a specific pod')
parser_podvulns.set_defaults(func=vulns)
parser_podvulns.add_argument('--pod', type=str, help='Name of the pod', dest='pod')
args = parser.parse_args()
if len(sys.argv) < 2:
parser.print_usage()
sys.exit(1)
args.func(args)