diff --git a/api/v1/open5gs_types.go b/api/v1/open5gs_types.go index 9ee73c1..4c5c73c 100644 --- a/api/v1/open5gs_types.go +++ b/api/v1/open5gs_types.go @@ -53,6 +53,8 @@ type Open5GSFunction struct { Service []Open5GSService `json:"service,omitempty" default:"{\"name\":\"\",\"port\":0,\"serviceType\":\"\"}"` GTPUDev string `json:"gtpuDev,omitempty" default:"eth0"` DeploymentAnnotations map[string]string `json:"deploymentAnnotations,omitempty"` + // Unprivileged runs the UPF without privileged:true/root (UPF only). + Unprivileged *bool `json:"unprivileged,omitempty" default:"false"` } type Open5GSService struct { diff --git a/api/v1/zz_generated.deepcopy.go b/api/v1/zz_generated.deepcopy.go index 7ce0290..f84ae82 100644 --- a/api/v1/zz_generated.deepcopy.go +++ b/api/v1/zz_generated.deepcopy.go @@ -96,6 +96,11 @@ func (in *Open5GSFunction) DeepCopyInto(out *Open5GSFunction) { (*out)[key] = val } } + if in.Unprivileged != nil { + in, out := &in.Unprivileged, &out.Unprivileged + *out = new(bool) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Open5GSFunction. diff --git a/charts/open5gs-operator/templates/open5gs-crd.yaml b/charts/open5gs-operator/templates/open5gs-crd.yaml index a67ee79..a333e94 100644 --- a/charts/open5gs-operator/templates/open5gs-crd.yaml +++ b/charts/open5gs-operator/templates/open5gs-crd.yaml @@ -65,6 +65,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object ausf: properties: @@ -91,6 +95,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object bsf: properties: @@ -117,6 +125,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object configuration: properties: @@ -165,6 +177,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object mongoDBVersion: type: string @@ -193,6 +209,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object nssf: properties: @@ -219,6 +239,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object open5gsImage: type: string @@ -247,6 +271,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object scp: properties: @@ -273,6 +301,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object smf: properties: @@ -299,6 +331,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object udm: properties: @@ -325,6 +361,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object udr: properties: @@ -351,6 +391,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object upf: properties: @@ -377,6 +421,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object webui: properties: @@ -403,6 +451,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object webuiImage: type: string diff --git a/config/crd/bases/net.gradiant.org_open5gses.yaml b/config/crd/bases/net.gradiant.org_open5gses.yaml index 678cc69..9cb244c 100644 --- a/config/crd/bases/net.gradiant.org_open5gses.yaml +++ b/config/crd/bases/net.gradiant.org_open5gses.yaml @@ -64,6 +64,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object ausf: properties: @@ -90,6 +94,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object bsf: properties: @@ -116,6 +124,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object configuration: properties: @@ -164,6 +176,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object mongoDBVersion: type: string @@ -192,6 +208,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object nssf: properties: @@ -218,6 +238,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object open5gsImage: type: string @@ -246,6 +270,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object scp: properties: @@ -272,6 +300,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object smf: properties: @@ -298,6 +330,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object udm: properties: @@ -324,6 +360,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object udr: properties: @@ -350,6 +390,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object upf: properties: @@ -376,6 +420,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object webui: properties: @@ -402,6 +450,10 @@ spec: type: boolean serviceMonitor: type: boolean + unprivileged: + description: Unprivileged runs the UPF without privileged:true/root + (UPF only). + type: boolean type: object webuiImage: type: string diff --git a/internal/controller/open5gs_controller.go b/internal/controller/open5gs_controller.go index 102a4a1..9621d5e 100644 --- a/internal/controller/open5gs_controller.go +++ b/internal/controller/open5gs_controller.go @@ -755,8 +755,9 @@ func (r *Open5GSReconciler) reconcileUDR(ctx context.Context, req ctrl.Request, func (r *Open5GSReconciler) reconcileUPF(ctx context.Context, req ctrl.Request, open5gs *netv1.Open5GS, logger logr.Logger) error { componentName := "UPF" gtpuDev := open5gs.Spec.UPF.GTPUDev + unprivileged := open5gs.Spec.UPF.Unprivileged != nil && *open5gs.Spec.UPF.Unprivileged configMap := CreateUPFConfigMap(req.Namespace, open5gs.Name, open5gs.Spec.Configuration, *open5gs.Spec.UPF.Metrics, gtpuDev) - entrypointConfigMap := CreateUPFEntrypointConfigMap(req.Namespace, open5gs.Name) + entrypointConfigMap := CreateUPFEntrypointConfigMap(req.Namespace, open5gs.Name, unprivileged) envVars := []corev1.EnvVar{} pfcpService := netv1.Open5GSService{Name: "pfcp"} @@ -795,7 +796,7 @@ func (r *Open5GSReconciler) reconcileUPF(ctx context.Context, req ctrl.Request, serviceAccount = CreateServiceAccount(req.Namespace, open5gs.Name, componentName) serviceAccountName = serviceAccount.Name } - deployment := CreateUPFDeployment(req.Namespace, open5gs.Name, open5gs.Spec.Open5GSImage, envVars, *open5gs.Spec.UPF.Metrics, serviceAccountName, open5gs.Spec.UPF.DeploymentAnnotations) + deployment := CreateUPFDeployment(req.Namespace, open5gs.Name, open5gs.Spec.Open5GSImage, envVars, *open5gs.Spec.UPF.Metrics, serviceAccountName, open5gs.Spec.UPF.DeploymentAnnotations, unprivileged) return r.reconcileComponent(ctx, open5gs, componentName, logger, configMap, deployment, services, serviceMonitor, serviceAccount) } @@ -1271,6 +1272,10 @@ func setDefaultValues(open5gs *netv1.Open5GS) { defaultUPFServiceMonitor := true open5gs.Spec.UPF.ServiceMonitor = &defaultUPFServiceMonitor } + if open5gs.Spec.UPF.Unprivileged == nil { + defaultUPFUnprivileged := false + open5gs.Spec.UPF.Unprivileged = &defaultUPFUnprivileged + } if open5gs.Spec.WebUI.Enabled == nil { defaultWebUIEnabled := false open5gs.Spec.WebUI.Enabled = &defaultWebUIEnabled diff --git a/internal/controller/open5gs_resources.go b/internal/controller/open5gs_resources.go index 52e3ce0..1f71a4d 100644 --- a/internal/controller/open5gs_resources.go +++ b/internal/controller/open5gs_resources.go @@ -618,18 +618,8 @@ upf: } } -func CreateUPFEntrypointConfigMap(namespace, open5gsName string) *corev1.ConfigMap { - return &corev1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: open5gsName + "-upf-entrypoint", - Namespace: namespace, - Labels: map[string]string{ - "app.kubernetes.io/instance": open5gsName, - "app.kubernetes.io/name": strings.ToLower("upf"), - }, - }, - Data: map[string]string{ - "k8s-entrypoint.sh": ` +func CreateUPFEntrypointConfigMap(namespace, open5gsName string, unprivileged bool) *corev1.ConfigMap { + script := ` #!/bin/bash set -e @@ -649,12 +639,55 @@ echo "Enable NAT for 10.45.0.0/16 and device ogstun" iptables -t nat -A POSTROUTING -s 10.45.0.0/16 ! -o ogstun -j MASQUERADE; $@ -`, +` + if unprivileged { + // Non-root, capability-only variant: the TUN device is created as a + // PERSISTENT device owned by the main container's UID (1001), which + // lets a non-root, zero-capability process attach to it afterward + // (Linux only requires CAP_NET_ADMIN to CREATE a TUN device, not to + // attach to one it already owns). net.ipv4.ip_forward is deliberately + // NOT set here: /proc/sys is read-only inside a non-privileged + // container regardless of capabilities/UID, so it must instead be set + // via the pod's declarative securityContext.sysctls field (see + // CreateUPFDeployment), which requires the cluster's kubelet to allow + // net.ipv4.ip_forward as an unsafe sysctl. + script = ` +#!/bin/bash +set -e + +echo "Executing k8s customized entrypoint.sh (unprivileged)" +echo "Creating net device ogstun" +if grep "ogstun" /proc/net/dev > /dev/null; then + echo "Warning: Net device ogstun already exists! may you need to set createDev: false"; + exit 1 +fi + +ip tuntap add name ogstun mode tun user 1001 +ip link set ogstun up +echo "Setting IP 10.45.0.1 to device ogstun" +ip addr add 10.45.0.1/16 dev ogstun; +echo "Enable NAT for 10.45.0.0/16 and device ogstun" +iptables -t nat -A POSTROUTING -s 10.45.0.0/16 ! -o ogstun -j MASQUERADE; + +$@ +` + } + return &corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{ + Name: open5gsName + "-upf-entrypoint", + Namespace: namespace, + Labels: map[string]string{ + "app.kubernetes.io/instance": open5gsName, + "app.kubernetes.io/name": strings.ToLower("upf"), + }, + }, + Data: map[string]string{ + "k8s-entrypoint.sh": script, }, } } -func CreateUPFDeployment(namespace, open5gsName, image string, envVars []corev1.EnvVar, metrics bool, serviceAccountName string, deploymentAnnotations map[string]string) *appsv1.Deployment { +func CreateUPFDeployment(namespace, open5gsName, image string, envVars []corev1.EnvVar, metrics bool, serviceAccountName string, deploymentAnnotations map[string]string, unprivileged bool) *appsv1.Deployment { var ports []corev1.ContainerPort if metrics { ports = []corev1.ContainerPort{ @@ -691,6 +724,147 @@ func CreateUPFDeployment(namespace, open5gsName, image string, envVars []corev1. if serviceAccountName == "" { serviceAccountName = "default" } + + // Default: today's privileged/root behavior, unchanged. + mainSecurityContext := &corev1.SecurityContext{ + Capabilities: &corev1.Capabilities{ + Add: []corev1.Capability{"NET_ADMIN"}, + }, + Privileged: boolPtr(true), + RunAsNonRoot: boolPtr(false), + RunAsUser: int64Ptr(0), + RunAsGroup: int64Ptr(0), + } + initSecurityContext := &corev1.SecurityContext{ + Capabilities: &corev1.Capabilities{ + Add: []corev1.Capability{"NET_ADMIN"}, + }, + Privileged: boolPtr(true), + RunAsNonRoot: boolPtr(false), + RunAsUser: int64Ptr(0), + RunAsGroup: int64Ptr(0), + } + mainVolumeMounts := []corev1.VolumeMount{ + { + Name: "config", + MountPath: "/opt/open5gs/etc/open5gs/upf.yaml", + SubPath: "upf.yaml", + }, + } + initVolumeMounts := []corev1.VolumeMount{ + { + Name: "entrypoint", + MountPath: "/k8s-entrypoint.sh", + SubPath: "k8s-entrypoint.sh", + }, + } + volumes := []corev1.Volume{ + { + Name: "config", + VolumeSource: corev1.VolumeSource{ + ConfigMap: &corev1.ConfigMapVolumeSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: open5gsName + "-upf", + }, + DefaultMode: int32Ptr(420), + }, + }, + }, + { + Name: "entrypoint", + VolumeSource: corev1.VolumeSource{ + ConfigMap: &corev1.ConfigMapVolumeSource{ + LocalObjectReference: corev1.LocalObjectReference{ + Name: open5gsName + "-upf-entrypoint", + }, + DefaultMode: int32Ptr(511), + }, + }, + }, + } + podSecurityContext := &corev1.PodSecurityContext{ + FSGroup: int64Ptr(1001), + } + mainCommand := []string(nil) + mainArgs := []string{"open5gs-upfd"} + + if unprivileged { + // Main container: no capabilities at all. It only attaches to the + // persistent, already-owned TUN device the init container created - + // Linux doesn't require CAP_NET_ADMIN to attach to a TUN device the + // calling UID already owns, only to create one. + // + // Neither container sets seLinuxOptions here even though SELinux- + // enforcing nodes (e.g. RHCOS/OpenShift) require type spc_t for tun + // device access (the default container_t domain has no policy + // allowing chr_file access to devices of type tun_tap_device_t, + // regardless of capabilities or UID) - the level half of that pair is + // namespace-specific (SCC MustRunAs auto-assigns it per project) and + // can't be hardcoded here. Setting only Type at the container level + // without a matching Level fails SCC validation outright. This is + // left entirely to the bound SCC's own seLinuxContext default + // instead (see the open5gs-upf-unprivileged SCC in the deployment + // examples), which fills in both consistently. + mainSecurityContext = &corev1.SecurityContext{ + Capabilities: &corev1.Capabilities{ + Drop: []corev1.Capability{"ALL"}, + }, + Privileged: boolPtr(false), + RunAsNonRoot: boolPtr(true), + RunAsUser: int64Ptr(1001), + RunAsGroup: int64Ptr(1001), + } + // The image's own default entrypoint (/entrypoint.sh, invoked + // implicitly since no Command is set) redundantly redoes the same + // tun/NAT/sysctl setup the init container already did, unconditionally, + // every time its Args match "open5gs-upfd" - requiring the same + // elevated privileges the main container is specifically trying to + // avoid here. Bypassing it and invoking the real binary directly + // skips that redundant (and here, privileged-only) work entirely. + mainCommand = []string{"/opt/open5gs/bin/open5gs-upfd"} + mainArgs = []string{"-c", "/opt/open5gs/etc/open5gs/upf.yaml"} + // Init container: root (not privileged) so CAP_NET_ADMIN is actually + // effective - Kubernetes does not set ambient/inheritable capabilities + // for non-root containers, so a non-root container requesting + // NET_ADMIN here would have it in its bounding set only, never + // effective. Root does not have that problem: effective capabilities + // for a root process come directly from the bounding set. + initSecurityContext = &corev1.SecurityContext{ + Capabilities: &corev1.Capabilities{ + Drop: []corev1.Capability{"ALL"}, + Add: []corev1.Capability{"NET_ADMIN"}, + }, + Privileged: boolPtr(false), + RunAsUser: int64Ptr(0), + RunAsGroup: int64Ptr(0), + } + tunDeviceHostPathType := corev1.HostPathCharDev + volumes = append(volumes, corev1.Volume{ + Name: "tun-device", + VolumeSource: corev1.VolumeSource{ + HostPath: &corev1.HostPathVolumeSource{ + Path: "/dev/net/tun", + Type: &tunDeviceHostPathType, + }, + }, + }) + mainVolumeMounts = append(mainVolumeMounts, corev1.VolumeMount{ + Name: "tun-device", + MountPath: "/dev/net/tun", + }) + initVolumeMounts = append(initVolumeMounts, corev1.VolumeMount{ + Name: "tun-device", + MountPath: "/dev/net/tun", + }) + // net.ipv4.ip_forward cannot be set from inside the container even as + // root (/proc/sys is read-only regardless of capabilities/UID); it + // must go through the pod's declarative sysctls, which requires the + // cluster's kubelet to allow it as an unsafe sysctl. + podSecurityContext.Sysctls = []corev1.Sysctl{ + {Name: "net.ipv4.ip_forward", Value: "1"}, + } + } + return &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: open5gsName + "-upf", @@ -720,58 +894,18 @@ func CreateUPFDeployment(namespace, open5gsName, image string, envVars []corev1. ServiceAccountName: serviceAccountName, Containers: []corev1.Container{ { - Name: "open5gs-upf", - Image: image, - Args: []string{"open5gs-upfd"}, - Ports: ports, - Env: envVars, - VolumeMounts: []corev1.VolumeMount{ - { - Name: "config", - MountPath: "/opt/open5gs/etc/open5gs/upf.yaml", - SubPath: "upf.yaml", - }, - }, - SecurityContext: &corev1.SecurityContext{ - Capabilities: &corev1.Capabilities{ - Add: []corev1.Capability{ - "NET_ADMIN", - }, - }, - Privileged: boolPtr(true), - RunAsNonRoot: boolPtr(false), - RunAsUser: int64Ptr(0), - RunAsGroup: int64Ptr(0), - }, - }, - }, - Volumes: []corev1.Volume{ - { - Name: "config", - VolumeSource: corev1.VolumeSource{ - ConfigMap: &corev1.ConfigMapVolumeSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: open5gsName + "-upf", - }, - DefaultMode: int32Ptr(420), - }, - }, - }, - { - Name: "entrypoint", - VolumeSource: corev1.VolumeSource{ - ConfigMap: &corev1.ConfigMapVolumeSource{ - LocalObjectReference: corev1.LocalObjectReference{ - Name: open5gsName + "-upf-entrypoint", - }, - DefaultMode: int32Ptr(511), - }, - }, + Name: "open5gs-upf", + Image: image, + Command: mainCommand, + Args: mainArgs, + Ports: ports, + Env: envVars, + VolumeMounts: mainVolumeMounts, + SecurityContext: mainSecurityContext, }, }, - SecurityContext: &corev1.PodSecurityContext{ - FSGroup: int64Ptr(1001), - }, + Volumes: volumes, + SecurityContext: podSecurityContext, InitContainers: []corev1.Container{ { Name: "tun-create", @@ -781,24 +915,8 @@ func CreateUPFDeployment(namespace, open5gsName, image string, envVars []corev1. "-c", "/k8s-entrypoint.sh", }, - VolumeMounts: []corev1.VolumeMount{ - { - Name: "entrypoint", - MountPath: "/k8s-entrypoint.sh", - SubPath: "k8s-entrypoint.sh", - }, - }, - SecurityContext: &corev1.SecurityContext{ - Capabilities: &corev1.Capabilities{ - Add: []corev1.Capability{ - "NET_ADMIN", - }, - }, - Privileged: boolPtr(true), - RunAsNonRoot: boolPtr(false), - RunAsUser: int64Ptr(0), - RunAsGroup: int64Ptr(0), - }, + VolumeMounts: initVolumeMounts, + SecurityContext: initSecurityContext, }, }, }, diff --git a/internal/controller/open5gs_resources_upf_test.go b/internal/controller/open5gs_resources_upf_test.go new file mode 100644 index 0000000..f70b630 --- /dev/null +++ b/internal/controller/open5gs_resources_upf_test.go @@ -0,0 +1,143 @@ +/* + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ + +package controller + +import ( + "strings" + "testing" + + corev1 "k8s.io/api/core/v1" +) + +func TestCreateUPFDeploymentDefaultUnchanged(t *testing.T) { + dep := CreateUPFDeployment("default", "test", "docker.io/gradiant/open5gs:2.7.5", nil, true, "", nil, false) + + main := dep.Spec.Template.Spec.Containers[0] + if main.SecurityContext.Privileged == nil || !*main.SecurityContext.Privileged { + t.Error("expected main container Privileged=true when unprivileged=false") + } + if main.SecurityContext.RunAsUser == nil || *main.SecurityContext.RunAsUser != 0 { + t.Error("expected main container RunAsUser=0 when unprivileged=false") + } + + if len(main.Command) != 0 { + t.Error("expected no Command override on main container when unprivileged=false") + } + if len(main.Args) != 1 || main.Args[0] != "open5gs-upfd" { + t.Error("expected main container Args to be unchanged (open5gs-upfd) when unprivileged=false") + } + + init := dep.Spec.Template.Spec.InitContainers[0] + if init.SecurityContext.Privileged == nil || !*init.SecurityContext.Privileged { + t.Error("expected init container Privileged=true when unprivileged=false") + } + + for _, v := range dep.Spec.Template.Spec.Volumes { + if v.Name == "tun-device" { + t.Error("did not expect a tun-device volume when unprivileged=false") + } + } + if dep.Spec.Template.Spec.SecurityContext.Sysctls != nil { + t.Error("did not expect pod-level sysctls when unprivileged=false") + } +} + +func TestCreateUPFDeploymentUnprivileged(t *testing.T) { + dep := CreateUPFDeployment("default", "test", "docker.io/gradiant/open5gs:2.7.5", nil, true, "", nil, true) + + main := dep.Spec.Template.Spec.Containers[0] + if main.SecurityContext.Privileged == nil || *main.SecurityContext.Privileged { + t.Error("expected main container Privileged=false when unprivileged=true") + } + if main.SecurityContext.RunAsNonRoot == nil || !*main.SecurityContext.RunAsNonRoot { + t.Error("expected main container RunAsNonRoot=true when unprivileged=true") + } + if main.SecurityContext.RunAsUser == nil || *main.SecurityContext.RunAsUser != 1001 { + t.Error("expected main container RunAsUser=1001 when unprivileged=true") + } + if len(main.SecurityContext.Capabilities.Add) != 0 { + t.Error("expected main container to add zero capabilities when unprivileged=true") + } + if len(main.SecurityContext.Capabilities.Drop) != 1 || main.SecurityContext.Capabilities.Drop[0] != "ALL" { + t.Error("expected main container to drop ALL capabilities when unprivileged=true") + } + if main.SecurityContext.SELinuxOptions != nil { + t.Error("expected no explicit seLinuxOptions on main container - left to the bound SCC's own default") + } + if len(main.Command) != 1 || main.Command[0] != "/opt/open5gs/bin/open5gs-upfd" { + t.Error("expected main container Command to bypass the image's own entrypoint wrapper when unprivileged=true") + } + if len(main.Args) != 2 || main.Args[0] != "-c" || main.Args[1] != "/opt/open5gs/etc/open5gs/upf.yaml" { + t.Error("expected main container Args to pass the config path directly when unprivileged=true") + } + + init := dep.Spec.Template.Spec.InitContainers[0] + if init.SecurityContext.Privileged == nil || *init.SecurityContext.Privileged { + t.Error("expected init container Privileged=false when unprivileged=true") + } + if init.SecurityContext.RunAsUser == nil || *init.SecurityContext.RunAsUser != 0 { + t.Error("expected init container RunAsUser=0 (root) when unprivileged=true") + } + if len(init.SecurityContext.Capabilities.Add) != 1 || init.SecurityContext.Capabilities.Add[0] != "NET_ADMIN" { + t.Error("expected init container to add only NET_ADMIN when unprivileged=true") + } + if init.SecurityContext.SELinuxOptions != nil { + t.Error("expected no explicit seLinuxOptions on init container - left to the bound SCC's own default") + } + + foundTunVolume := false + for _, v := range dep.Spec.Template.Spec.Volumes { + if v.Name == "tun-device" { + foundTunVolume = true + if v.HostPath == nil || v.HostPath.Path != "/dev/net/tun" { + t.Error("expected tun-device volume to be a hostPath mount of /dev/net/tun") + } + if v.HostPath.Type == nil || *v.HostPath.Type != corev1.HostPathCharDev { + t.Error("expected tun-device hostPath type to be CharDevice") + } + } + } + if !foundTunVolume { + t.Error("expected a tun-device volume when unprivileged=true") + } + + foundMainMount := false + for _, m := range main.VolumeMounts { + if m.Name == "tun-device" && m.MountPath == "/dev/net/tun" { + foundMainMount = true + } + } + if !foundMainMount { + t.Error("expected main container to mount tun-device at /dev/net/tun") + } + + sysctls := dep.Spec.Template.Spec.SecurityContext.Sysctls + if len(sysctls) != 1 || sysctls[0].Name != "net.ipv4.ip_forward" || sysctls[0].Value != "1" { + t.Error("expected pod-level sysctls to set net.ipv4.ip_forward=1") + } +} + +func TestCreateUPFEntrypointConfigMapUnprivileged(t *testing.T) { + defaultCM := CreateUPFEntrypointConfigMap("default", "test", false) + unprivCM := CreateUPFEntrypointConfigMap("default", "test", true) + + defaultScript := defaultCM.Data["k8s-entrypoint.sh"] + unprivScript := unprivCM.Data["k8s-entrypoint.sh"] + + if !strings.Contains(defaultScript, "sysctl -w net.ipv4.ip_forward=1") { + t.Error("expected default script to set ip_forward via sysctl -w in-container") + } + if strings.Contains(unprivScript, "sysctl -w") { + t.Error("unprivileged script must not attempt sysctl -w (blocked by read-only /proc/sys)") + } + if !strings.Contains(unprivScript, "ip tuntap add name ogstun mode tun user 1001") { + t.Error("expected unprivileged script to create a persistent tun device owned by uid 1001") + } + if !strings.Contains(unprivScript, "iptables -t nat -A POSTROUTING") { + t.Error("expected unprivileged script to still add the NAT rule") + } +}