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
|
from kubernetes import client, config, watch
import os
import uuid
import json
import tempfile
import time
def check_filesharerequest(obj, crds, group, version, filesharerequests_plural):
fsr = crds.list_namespaced_custom_object(
group, version, "shares", filesharerequests_plural
)
if len(fsr["items"]) > 5:
return (
False,
"Five FilleSharedRequests are deployed somewhere in the cluster, you need to delete them first!",
)
fr = json.loads(json.dumps(obj))
if "spec" not in fr:
return False, "FilleSharedRequest: Missing Spec"
if "shareName" not in fr["spec"]:
return False, "FilleSharedRequest: Missing Spec shareName"
if "accessModes" not in fr["spec"]:
return False, "FilleSharedRequest: Missing Spec accessModes"
# Check the accessModes
valid_modes = ("ReadWriteOnce", "ReadOnlyMany", "ReadWriteMany", "ReadWriteOncePod")
if not all(mode in valid_modes for mode in fr["spec"]["accessModes"]):
return False, "FilleSharedRequest: Invalid Spec accessModes values, "
"only allow ReadWriteOnce, ReadOnlyMany, ReadWriteMany, ReadWriteOncePod"
if "storage" not in fr["spec"]:
return False, "FilleSharedRequest: Missing Spec storage, must be less than 1Gi"
return True, "Worked"
def create_pv_pvc(
client, pvcobj, crds, group, version, filesharerequests_plural, pv_name, pvc_name
):
v1 = client.CoreV1Api()
pvc_spec = pvcobj["spec"]
# Define PV
pv = client.V1PersistentVolume(
api_version="v1",
kind="PersistentVolume",
metadata=client.V1ObjectMeta(name=pv_name),
spec=client.V1PersistentVolumeSpec(
capacity={"storage": pvc_spec["storage"]},
access_modes=pvc_spec["accessModes"],
persistent_volume_reclaim_policy="Delete",
storage_class_name=pvc_spec["shareName"],
host_path=client.V1HostPathVolumeSource(path=tempfile.mkdtemp()),
),
)
# Define PVC
pvc = client.V1PersistentVolumeClaim(
api_version="v1",
kind="PersistentVolumeClaim",
metadata=client.V1ObjectMeta(name=pvc_name, namespace="shares"),
spec=client.V1PersistentVolumeClaimSpec(
access_modes=pvc_spec["accessModes"],
resources=client.V1ResourceRequirements(
requests={"storage": pvc_spec["storage"]}
),
storage_class_name=pvc_spec["shareName"],
),
)
try:
# Create PVC
v1.create_namespaced_persistent_volume_claim(namespace="shares", body=pvc)
print(f"PersistentVolumeClaim {pvc.metadata.name} created.")
# Create PV
v1.create_persistent_volume(body=pv)
print(f"PersistentVolume {pv.metadata.name} created.")
return True
except client.exceptions.ApiException as e:
print(f"Exception when creating PV or PVC: {e}")
return False
def main():
# Define CRDs
version = "v1"
group = "ctf.r3kapig.com"
fileshare_kind = "FileShares"
fileshares_plural = "fileshares"
filesharerequests_plural = "filesharerequests"
# Load CRDs and V1 API
crds = client.CustomObjectsApi()
v1 = client.CoreV1Api()
while True:
print("Watching for filerequests...")
stream = watch.Watch().stream(
crds.list_namespaced_custom_object,
group,
version,
"shares",
filesharerequests_plural,
)
for event in stream:
t = event["type"]
filesharerequest = event["object"]
match t:
case "ADDED":
# Check wether it was already created
# Check if the filerequest is legal
checked, error = check_filesharerequest(
filesharerequest, crds, group, version, filesharerequests_plural
)
if not checked:
crds.create_namespaced_custom_object(
group,
version,
"shares",
fileshares_plural,
{
"apiVersion": f"{group}/{version}",
"kind": fileshare_kind,
"metadata": {
"name": f"{filesharerequest["metadata"]["name"]}-fileshare"
},
"spec": {
"podName": "",
"error": error,
},
},
)
continue
pv_name = f"{filesharerequest["metadata"]["name"]}-pv"
pvc_name = f"{filesharerequest["metadata"]["name"]}-pvc"
if not create_pv_pvc(
client,
filesharerequest,
crds,
group,
version,
filesharerequests_plural,
pv_name,
pvc_name,
):
print("Error create the pv and pvc")
continue
pod_name = f'{filesharerequest["metadata"]["name"]}-pod'
pod_spec = client.V1Pod(
api_version="v1",
kind="Pod",
metadata=client.V1ObjectMeta(
name=pod_name, labels={"app": "secure-pod"}
),
spec=client.V1PodSpec(
containers=[
client.V1Container(
name="my-container",
image="registry-docker:5000/busybox:1.34.1",
command=["bin/sh"],
args=["-c", "sleep inf"],
resources=client.V1ResourceRequirements(
limits={"cpu": "0.5", "memory": "300Mi"},
),
security_context=client.V1SecurityContext(
read_only_root_filesystem=True, # Set the root filesystem as read-only
run_as_non_root=True, # Run as non-root user
run_as_user=1000, # Specify the user ID
run_as_group=1000,
capabilities=client.V1Capabilities(
drop=["ALL"] # Drop all capabilities
),
allow_privilege_escalation=False, # Disallow privilege escalation
),
volume_mounts=[
client.V1VolumeMount(
mount_path="/my-sharefile",
name="fileshare-storage",
read_only=True,
)
],
)
],
volumes=[
client.V1Volume(
name="fileshare-storage",
persistent_volume_claim=client.V1PersistentVolumeClaimVolumeSource(
claim_name=pvc_name
),
)
],
automount_service_account_token=False,
),
)
try:
api_response = v1.create_namespaced_pod(
namespace="shares", body=pod_spec
)
# Waiting for Pod Running
start_time = time.time()
# Timeout 120
while time.time() - start_time < 120:
pod_status = v1.read_namespaced_pod_status(
namespace="shares", name=pod_name
)
current_status = pod_status.status.phase
if current_status != "Pending":
break
time.sleep(3)
print("Pod running with security configurations")
except Exception as e:
print(f"Exception when updating Pod: {e}")
error = f"Exception when updating Pod: {e}"
continue
# Return the result to fileshare
crds.create_namespaced_custom_object(
group,
version,
"shares",
fileshares_plural,
{
"apiVersion": f"{group}/{version}",
"kind": fileshare_kind,
"metadata": {
"name": f"{filesharerequest["metadata"]["name"]}-fileshare"
},
"spec": {
"podName": pod_name,
"error": error,
},
},
)
case "DELETED":
pv_name = f"{filesharerequest["metadata"]["name"]}-pv"
pvc_name = f"{filesharerequest["metadata"]["name"]}-pvc"
pod_name = f"{filesharerequest["metadata"]["name"]}-pod"
# Delete Pod
try:
api_response = v1.delete_namespaced_pod(
name=pod_name,
namespace="shares",
body=client.V1DeleteOptions(),
)
print("Pod deleted")
except Exception as e:
print(f"Exception when deleting Pod: {e}")
try:
crd_name = f"{fileshares_plural}.{group}"
api_response = crds.delete_namespaced_custom_object(
group,
version,
"shares",
fileshares_plural,
f"{filesharerequest["metadata"]["name"]}-fileshare",
)
except Exception as e:
print(f"Exception when deleting CustomResourceDefinition: {e}")
# Delete PVC
v1.delete_namespaced_persistent_volume_claim(
name=pvc_name, namespace="shares"
)
# Delete PV
v1.delete_persistent_volume(name=pv_name)
case _:
pass
if __name__ == "__main__":
print("Starting operator...")
try:
config.incluster_config.load_incluster_config()
except Exception as e:
print("Failed to load incluster config")
exit(1)
main()
|