-
Notifications
You must be signed in to change notification settings - Fork 10
/
yair.py
executable file
·304 lines (250 loc) · 10.8 KB
/
yair.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#!/usr/bin/env python3
"""
Gathers Vulnerability Information and outputs it in a fancy way :-)
"""
import os
import sys
import json
import requests
from tabulate import tabulate
import textwrap
import yaml
import argparse
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("--config", action="store", dest="config_file", default="/opt/yair/config/config.yaml",
help="Config file location. Defaults to /opt/yair/config/config.yaml")
arg_parser.add_argument("--no-namespace", action="store_true", dest="no_namespace", default=False,
help="If your image names doesnt contain the \"namespace\" and its not in the default \"library\" namespace.")
arg_parser.add_argument("--registry", action="store",
help="Overwrites the \"registry::host\" configfile option.")
arg_parser.add_argument("image", action="store",
help="The image you want to scan. if you provide no tag we will assume \"latest\". if you provide no namespace we will assume \"library\".")
args = arg_parser.parse_args()
try:
with open(args.config_file, 'r') as cfg:
config = yaml.load(cfg)
except yaml.parser.ParserError:
print("error while parsing config.yaml", file=sys.stderr)
exit(1)
except FileNotFoundError:
print("config file \"" + args.config_file + "\" not found - exiting")
exit(1)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 100)
sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 100)
image_score_fail_on=config['fail_on']['score']
big_vuln_fail_on=bool(config['fail_on']['big_vulnerability'])
docker_registry=config['registry']['host']
output=config['output']['format']
clair_server=config['clair']['host']
try:
rocket_chat_enable=True
rocket_hook_url = config['output']['rocketchat']['webhook_url']
rocket_receiver= config['output']['rocketchat']['receiver'].split(",")
except KeyError:
rocket_chat_enable=False
if args.registry != None:
docker_registry = args.registry
image = args.image
try:
image, image_tag = image.rsplit(':', 1)
except ValueError:
image_tag = "latest"
image_s = image.split('/')
if len(image_s) == 1:
if args.no_namespace == True:
image_name = image
else:
image_name = "library/" + image
elif len(image_s) >= 2:
image_name = image
def y_req(address, method, h=None, data=None):
if h is None:
h = {}
if data is None:
data = {}
try:
if method == "get":
req_result = requests.get(address, headers=h)
req_result.raise_for_status()
elif method == "post":
req_result = requests.post(address, headers=h, data=data)
req_result.raise_for_status()
elif method == "delete":
req_result = requests.delete(address, headers=h)
req_result.raise_for_status()
return req_result
except requests.exceptions.HTTPError as err:
print(err, file=sys.stderr)
exit(1)
except requests.exceptions.ConnectionError as err:
print("connection to {} failed".format(address), file=sys.stderr)
exit(1)
def get_image_manifest():
global registry_token
req_headers = {}
req_url = "https://" + docker_registry + "/v2/" + image_name + "/manifests/" + image_tag
req_headers['Accept'] = 'application/vnd.docker.distribution.manifest.v2+json'
try:
req_result = requests.get(req_url, headers=req_headers)
if req_result.status_code == 401:
auth_header = req_result.headers['WWW-Authenticate'].split(',')
registry_auth = auth_header[0].replace('Bearer realm=', '').replace('"', '')
registry_service = auth_header[1].replace('"', '')
registry_scope = auth_header[2].replace('"', '')
req_url = registry_auth + "?" + registry_service + "&" + registry_scope + "&offline_token"
req_result = y_req(req_url, "get")
data = json.loads(req_result.text)
registry_token = "Bearer " + data['token']
req_headers['Authorization'] = registry_token
else:
registry_token = ""
req_result.raise_for_status()
except requests.exceptions.HTTPError as err:
print(err, file=sys.stderr)
exit(1)
except requests.exceptions.ConnectionError as err:
print("connection to {} failed".format(req_url), file=sys.stderr)
exit(1)
req_url = "https://" + docker_registry + "/v2/" + image_name + "/manifests/" + image_tag
req_headers['Accept'] = 'application/vnd.docker.distribution.manifest.v2+json'
req_result = y_req(req_url, "get", h=req_headers)
if req_result.status_code == 404:
raise ValueError("image not found")
req_result.raise_for_status()
data = json.loads(req_result.text)
return data
def get_image_layers():
manifest = get_image_manifest()
if manifest['schemaVersion'] == 1:
result = list(map(lambda x: x['blobSum'], manifest['fsLayers']))
result.reverse() # schema v1 need the reversed order
# result.remove('a3ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b46d4') # layer needs to be filtered
return result
elif manifest['schemaVersion'] == 2:
result = list(map(lambda x: x['digest'], manifest['layers']))
return result
else:
raise NotImplementedError("unknown schema version")
def analyse_image():
# delete old check results
try:
req_url = "http://" + clair_server + "/v1/layers/" + layers[-1]
req_result = requests.delete(req_url)
if req_result.status_code != 404:
req_result.raise_for_status()
except requests.exceptions.HTTPError as err:
print(err, file=sys.stderr)
exit(1)
except requests.exceptions.ConnectionError as err:
print("connection to {} failed".format(req_url), file=sys.stderr)
exit(1)
for i in range(0, len(layers)):
json_data = { "Layer": { "Name": "", "Path": "", "Headers": { "Authorization": "" }, "ParentName": "", "Format": "" }} # json template
json_data['Layer']['Name'] = layers[i]
json_data['Layer']['Path'] = "https://" + docker_registry + "/v2/" + image_name + "/blobs/" + layers[i]
json_data['Layer']['Headers']['Authorization'] = registry_token
if i == 0:
json_data['Layer']['ParentName'] = ""
else:
json_data['Layer']['ParentName'] = layers[i-1]
json_data['Layer']['Format'] = "Docker"
req_url = "http://" + clair_server + "/v1/layers"
req_headers = { 'Content-Type': 'application/json' }
y_req(req_url, "post", data=json.dumps(json_data), h=req_headers)
def get_image_info():
vuln_data = []
severitys= ["Unknown","Negligible","Low", "Medium", "High", "Critical", "Defcon1"]
req_url = "http://" + clair_server + "/v1/layers/" + layers[-1] + "?features&vulnerabilities"
req_headers = {'Content-Type': 'application/json'}
req_result = y_req(req_url, "get", h=req_headers)
data = req_result.json()
if 'Features' not in data['Layer']:
print("could not find any package in the given image", file=sys.stderr)
exit(0)
data = data['Layer']['Features']
for d in data:
if "Vulnerabilities" in d:
for v in d['Vulnerabilities']:
vd = dict (
package_name = d['Name'],
installed_version = d['Version'],
namespace_name = v['NamespaceName'],
cve_severity = v['Severity'],
cve_name = v['Name'],
cve_link = v['Link'],
)
if 'FixedBy' in v:
vd['cve_fixed_version'] = v['FixedBy']
else:
vd['cve_fixed_version'] = ""
if 'Description' in v:
vd['cve_desc'] = v['Description']
else:
vd['cve_desc'] = ""
vuln_data.append(vd)
for i in range(0, len(severitys)):
if severitys[i] == vd['cve_severity']:
vd['cve_severity_nr'] = i
return vuln_data
def send_to_rocket(message, emoji):
if rocket_chat_enable:
for receiver in rocket_receiver:
payload = {"icon_emoji": emoji, "channel": receiver, "text": message}
y_req(rocket_hook_url, "post", data=json.dumps(payload))
def output_data():
image_score = 0
big_vuln = False
table = []
vuln_data.sort(key=lambda vuln: vuln['cve_severity_nr'], reverse=True)
for vuln in vuln_data:
if vuln['cve_severity_nr'] >= 4:
big_vuln = True
if vuln['cve_fixed_version'] != "":
image_score += vuln['cve_severity_nr']**4
if output == "table":
headers = ["Package\nInstalled Version", "CVE Name\nSeverity", "CVE Link\nCVE Description", "Version with fix"]
for vuln in vuln_data:
vuln['cve_desc'] = vuln['cve_link'] + "\n\n" + textwrap.fill(vuln['cve_desc'], 64)
vuln['package'] = vuln['package_name'] + "\n\n" + vuln['installed_version']
vuln['cve'] = vuln['cve_name'] + "\n\n" + vuln['cve_severity']
table.append([vuln['package'], vuln['cve'], vuln['cve_desc'], vuln['cve_fixed_version']])
print(tabulate(table, headers=headers, tablefmt="grid"),
file=sys.stdout)
elif output == "short-table":
headers = ["Package", "CVE Name", "Severity", "Version with fix"]
for vuln in vuln_data:
table.append([vuln['package_name'], vuln['cve_name'], vuln['cve_severity'], vuln['cve_fixed_version']])
print(tabulate(table, headers=headers, tablefmt="psql"),
file=sys.stdout)
elif output == "json":
print(json.dumps(vuln_data), file=sys.stdout)
elif output == "quiet":
if big_vuln and big_vuln_fail_on:
exit(2)
elif image_score < image_score_fail_on:
exit(0)
else:
exit(2)
print("scan result for: {}:{}".format(image_name, image_tag),
file=sys.stderr)
if big_vuln and big_vuln_fail_on:
send_to_rocket('The security scan for "{}:{}" has found an '
'vulnerability with severity high or higher!'
.format(image_name, image_tag),
":information_source:")
print("the image has \"high\" vulnerabilities", file=sys.stderr)
exit(2)
elif image_score < image_score_fail_on:
exit(0)
else:
send_to_rocket('The security scan for "{}:{}" has found an '
'vulnerability score of {}!'
.format(image_name, image_tag, image_score),
":information_source:")
print("the image has to many fixable vulnerabilities", file=sys.stderr)
exit(2)
if __name__ == '__main__':
layers = get_image_layers()
analyse_image()
vuln_data = get_image_info()
output_data()