Skip to content

Commit

Permalink
AppArmor PodSecurityPolicy implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
tallclair committed Aug 18, 2016
1 parent 21b0cbd commit 20c6802
Show file tree
Hide file tree
Showing 11 changed files with 492 additions and 4 deletions.
1 change: 1 addition & 0 deletions hack/.linted_packages
Original file line number Diff line number Diff line change
Expand Up @@ -199,3 +199,4 @@ test/soak/cauldron
test/soak/serve_hostnames
third_party/forked/golang/expansion
pkg/util/maps
pkg/security/podsecuritypolicy/apparmor
19 changes: 19 additions & 0 deletions pkg/apis/extensions/validation/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import (
apivalidation "k8s.io/kubernetes/pkg/api/validation"
"k8s.io/kubernetes/pkg/apis/extensions"
"k8s.io/kubernetes/pkg/labels"
"k8s.io/kubernetes/pkg/security/apparmor"
psputil "k8s.io/kubernetes/pkg/security/podsecuritypolicy/util"
"k8s.io/kubernetes/pkg/util/intstr"
"k8s.io/kubernetes/pkg/util/sets"
Expand Down Expand Up @@ -552,6 +553,7 @@ var ValidatePodSecurityPolicyName = apivalidation.NameIsDNSSubdomain
func ValidatePodSecurityPolicy(psp *extensions.PodSecurityPolicy) field.ErrorList {
allErrs := field.ErrorList{}
allErrs = append(allErrs, apivalidation.ValidateObjectMeta(&psp.ObjectMeta, false, ValidatePodSecurityPolicyName, field.NewPath("metadata"))...)
allErrs = append(allErrs, ValidatePodSecurityPolicySpecificAnnotations(psp.Annotations, field.NewPath("metadata").Child("annotations"))...)
allErrs = append(allErrs, ValidatePodSecurityPolicySpec(&psp.Spec, field.NewPath("spec"))...)
return allErrs
}
Expand All @@ -570,6 +572,23 @@ func ValidatePodSecurityPolicySpec(spec *extensions.PodSecurityPolicySpec, fldPa
return allErrs
}

func ValidatePodSecurityPolicySpecificAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList {
allErrs := field.ErrorList{}
if p := annotations[apparmor.DefaultProfileAnnotationKey]; p != "" {
if err := apparmor.ValidateProfileFormat(p); err != nil {
allErrs = append(allErrs, field.Invalid(fldPath.Key(apparmor.DefaultProfileAnnotationKey), p, err.Error()))
}
}
if allowed := annotations[apparmor.AllowedProfilesAnnotationKey]; allowed != "" {
for _, p := range strings.Split(allowed, ",") {
if err := apparmor.ValidateProfileFormat(p); err != nil {
allErrs = append(allErrs, field.Invalid(fldPath.Key(apparmor.AllowedProfilesAnnotationKey), allowed, err.Error()))
}
}
}
return allErrs
}

// validatePSPSELinux validates the SELinux fields of PodSecurityPolicy.
func validatePSPSELinux(fldPath *field.Path, seLinux *extensions.SELinuxStrategyOptions) field.ErrorList {
allErrs := field.ErrorList{}
Expand Down
33 changes: 32 additions & 1 deletion pkg/apis/extensions/validation/validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/apis/extensions"
"k8s.io/kubernetes/pkg/security/apparmor"
psputil "k8s.io/kubernetes/pkg/security/podsecuritypolicy/util"
"k8s.io/kubernetes/pkg/util/intstr"
"k8s.io/kubernetes/pkg/util/validation/field"
Expand Down Expand Up @@ -1510,7 +1511,9 @@ func TestValidateReplicaSet(t *testing.T) {
func TestValidatePodSecurityPolicy(t *testing.T) {
validPSP := func() *extensions.PodSecurityPolicy {
return &extensions.PodSecurityPolicy{
ObjectMeta: api.ObjectMeta{Name: "foo"},
ObjectMeta: api.ObjectMeta{
Name: "foo",
},
Spec: extensions.PodSecurityPolicySpec{
SELinux: extensions.SELinuxStrategyOptions{
Rule: extensions.SELinuxStrategyRunAsAny,
Expand Down Expand Up @@ -1584,6 +1587,15 @@ func TestValidatePodSecurityPolicy(t *testing.T) {
allowedCapListedInRequiredDrop.Spec.RequiredDropCapabilities = []api.Capability{"foo"}
allowedCapListedInRequiredDrop.Spec.AllowedCapabilities = []api.Capability{"foo"}

invalidAppArmorDefault := validPSP()
invalidAppArmorDefault.Annotations = map[string]string{
apparmor.DefaultProfileAnnotationKey: "not-good",
}
invalidAppArmorAllowed := validPSP()
invalidAppArmorAllowed.Annotations = map[string]string{
apparmor.AllowedProfilesAnnotationKey: apparmor.ProfileRuntimeDefault + ",not-good",
}

errorCases := map[string]struct {
psp *extensions.PodSecurityPolicy
errorType field.ErrorType
Expand Down Expand Up @@ -1664,6 +1676,16 @@ func TestValidatePodSecurityPolicy(t *testing.T) {
errorType: field.ErrorTypeInvalid,
errorDetail: "capability is listed in allowedCapabilities and requiredDropCapabilities",
},
"invalid AppArmor default profile": {
psp: invalidAppArmorDefault,
errorType: field.ErrorTypeInvalid,
errorDetail: "invalid AppArmor profile name: \"not-good\"",
},
"invalid AppArmor allowed profile": {
psp: invalidAppArmorAllowed,
errorType: field.ErrorTypeInvalid,
errorDetail: "invalid AppArmor profile name: \"not-good\"",
},
}

for k, v := range errorCases {
Expand Down Expand Up @@ -1700,6 +1722,12 @@ func TestValidatePodSecurityPolicy(t *testing.T) {
caseInsensitiveAllowedDrop.Spec.RequiredDropCapabilities = []api.Capability{"FOO"}
caseInsensitiveAllowedDrop.Spec.AllowedCapabilities = []api.Capability{"foo"}

validAppArmor := validPSP()
validAppArmor.Annotations = map[string]string{
apparmor.DefaultProfileAnnotationKey: apparmor.ProfileRuntimeDefault,
apparmor.AllowedProfilesAnnotationKey: apparmor.ProfileRuntimeDefault + "," + apparmor.ProfileNamePrefix + "foo",
}

successCases := map[string]struct {
psp *extensions.PodSecurityPolicy
}{
Expand All @@ -1718,6 +1746,9 @@ func TestValidatePodSecurityPolicy(t *testing.T) {
"comparison for allowed -> drop is case sensitive": {
psp: caseInsensitiveAllowedDrop,
},
"valid AppArmor annotations": {
psp: validAppArmor,
},
}

for k, v := range successCases {
Expand Down
13 changes: 13 additions & 0 deletions pkg/security/apparmor/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ import (
const (
// The prefix to an annotation key specifying a container profile.
ContainerAnnotationKeyPrefix = "container.apparmor.security.alpha.kubernetes.io/"
// The annotation key specifying the default AppArmor profile.
DefaultProfileAnnotationKey = "apparmor.security.alpha.kubernetes.io/defaultProfileName"
// The annotation key specifying the allowed AppArmor profiles.
AllowedProfilesAnnotationKey = "apparmor.security.alpha.kubernetes.io/allowedProfileNames"

// The profile specifying the runtime default.
ProfileRuntimeDefault = "runtime/default"
Expand All @@ -47,3 +51,12 @@ func isRequired(pod *api.Pod) bool {
func GetProfileName(pod *api.Pod, containerName string) string {
return pod.Annotations[ContainerAnnotationKeyPrefix+containerName]
}

// Sets the name of the profile to use with the container.
func SetProfileName(pod *api.Pod, containerName, profileName string) error {
if pod.Annotations == nil {
pod.Annotations = map[string]string{}
}
pod.Annotations[ContainerAnnotationKeyPrefix+containerName] = profileName
return nil
}
110 changes: 110 additions & 0 deletions pkg/security/podsecuritypolicy/apparmor/strategy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package apparmor

import (
"fmt"
"strings"

"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/security/apparmor"
"k8s.io/kubernetes/pkg/util/maps"
"k8s.io/kubernetes/pkg/util/validation/field"
)

// Strategy defines the interface for all AppArmor constraint strategies.
type Strategy interface {
// Generate updates the annotations based on constraint rules. The updates are applied to a copy
// of the annotations, and returned.
Generate(annotations map[string]string, container *api.Container) (map[string]string, error)
// Validate ensures that the specified values fall within the range of the strategy.
Validate(pod *api.Pod, container *api.Container) field.ErrorList
}

type strategy struct {
defaultProfile string
allowedProfiles map[string]bool
// For printing error messages (preserves order).
allowedProfilesString string
}

var _ Strategy = &strategy{}

// NewStrategy creates a new strategy that enforces AppArmor profile constraints.
func NewStrategy(pspAnnotations map[string]string) Strategy {
var allowedProfiles map[string]bool
if allowed, ok := pspAnnotations[apparmor.AllowedProfilesAnnotationKey]; ok {
profiles := strings.Split(allowed, ",")
allowedProfiles = make(map[string]bool, len(profiles))
for _, p := range profiles {
allowedProfiles[p] = true
}
}
return &strategy{
defaultProfile: pspAnnotations[apparmor.DefaultProfileAnnotationKey],
allowedProfiles: allowedProfiles,
allowedProfilesString: pspAnnotations[apparmor.AllowedProfilesAnnotationKey],
}
}

func (s *strategy) Generate(annotations map[string]string, container *api.Container) (map[string]string, error) {
copy := maps.CopySS(annotations)

if annotations[apparmor.ContainerAnnotationKeyPrefix+container.Name] != "" {
// Profile already set, nothing to do.
return copy, nil
}

if s.defaultProfile == "" {
// No default set.
return copy, nil
}

if copy == nil {
copy = map[string]string{}
}
// Add the default profile.
copy[apparmor.ContainerAnnotationKeyPrefix+container.Name] = s.defaultProfile

return copy, nil
}

func (s *strategy) Validate(pod *api.Pod, container *api.Container) field.ErrorList {
if s.allowedProfiles == nil {
// Unrestricted: allow all.
return nil
}

allErrs := field.ErrorList{}
fieldPath := field.NewPath("pod", "metadata", "annotations").Key(apparmor.ContainerAnnotationKeyPrefix + container.Name)

profile := apparmor.GetProfileName(pod, container.Name)
if profile == "" {
if len(s.allowedProfiles) > 0 {
allErrs = append(allErrs, field.Forbidden(fieldPath, "AppArmor profile must be set"))
return allErrs
}
return nil
}

if !s.allowedProfiles[profile] {
msg := fmt.Sprintf("%s is not an allowed profile. Allowed values: %q", profile, s.allowedProfilesString)
allErrs = append(allErrs, field.Forbidden(fieldPath, msg))
}

return allErrs
}

0 comments on commit 20c6802

Please sign in to comment.