admission_test.go 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package podsecuritypolicy
  14. import (
  15. "fmt"
  16. "reflect"
  17. "strings"
  18. "testing"
  19. "github.com/stretchr/testify/assert"
  20. v1 "k8s.io/api/core/v1"
  21. policy "k8s.io/api/policy/v1beta1"
  22. apiequality "k8s.io/apimachinery/pkg/api/equality"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. "k8s.io/apimachinery/pkg/util/diff"
  25. kadmission "k8s.io/apiserver/pkg/admission"
  26. admissiontesting "k8s.io/apiserver/pkg/admission/testing"
  27. "k8s.io/apiserver/pkg/authentication/serviceaccount"
  28. "k8s.io/apiserver/pkg/authentication/user"
  29. "k8s.io/apiserver/pkg/authorization/authorizer"
  30. "k8s.io/apiserver/pkg/authorization/authorizerfactory"
  31. utilfeature "k8s.io/apiserver/pkg/util/feature"
  32. "k8s.io/client-go/informers"
  33. featuregatetesting "k8s.io/component-base/featuregate/testing"
  34. "k8s.io/kubernetes/pkg/api/legacyscheme"
  35. kapi "k8s.io/kubernetes/pkg/apis/core"
  36. k8s_api_v1 "k8s.io/kubernetes/pkg/apis/core/v1"
  37. "k8s.io/kubernetes/pkg/controller"
  38. "k8s.io/kubernetes/pkg/features"
  39. "k8s.io/kubernetes/pkg/security/apparmor"
  40. kpsp "k8s.io/kubernetes/pkg/security/podsecuritypolicy"
  41. "k8s.io/kubernetes/pkg/security/podsecuritypolicy/seccomp"
  42. psputil "k8s.io/kubernetes/pkg/security/podsecuritypolicy/util"
  43. utilpointer "k8s.io/utils/pointer"
  44. )
  45. const defaultContainerName = "test-c"
  46. // NewTestAdmission provides an admission plugin with test implementations of internal structs.
  47. func NewTestAdmission(psps []*policy.PodSecurityPolicy, authz authorizer.Authorizer) *Plugin {
  48. informerFactory := informers.NewSharedInformerFactory(nil, controller.NoResyncPeriodFunc())
  49. store := informerFactory.Policy().V1beta1().PodSecurityPolicies().Informer().GetStore()
  50. for _, psp := range psps {
  51. store.Add(psp)
  52. }
  53. lister := informerFactory.Policy().V1beta1().PodSecurityPolicies().Lister()
  54. if authz == nil {
  55. authz = &TestAuthorizer{}
  56. }
  57. return &Plugin{
  58. Handler: kadmission.NewHandler(kadmission.Create, kadmission.Update),
  59. strategyFactory: kpsp.NewSimpleStrategyFactory(),
  60. authz: authz,
  61. lister: lister,
  62. }
  63. }
  64. // TestAuthorizer is a testing struct for testing that fulfills the authorizer interface.
  65. type TestAuthorizer struct {
  66. // usernameToNamespaceToAllowedPSPs contains the map of allowed PSPs.
  67. // if nil, all PSPs are allowed.
  68. usernameToNamespaceToAllowedPSPs map[string]map[string]map[string]bool
  69. // allowedAPIGroupName specifies an API Group name that contains PSP resources.
  70. // In order to be authorized, AttributesRecord must have this group name.
  71. // When empty, API Group name isn't taken into account.
  72. // TODO: remove this when PSP will be completely moved out of the extensions and we'll lookup only in "policy" group.
  73. allowedAPIGroupName string
  74. }
  75. func (t *TestAuthorizer) Authorize(a authorizer.Attributes) (authorized authorizer.Decision, reason string, err error) {
  76. if t.usernameToNamespaceToAllowedPSPs == nil {
  77. return authorizer.DecisionAllow, "", nil
  78. }
  79. allowedInNamespace := t.usernameToNamespaceToAllowedPSPs[a.GetUser().GetName()][a.GetNamespace()][a.GetName()]
  80. allowedClusterWide := t.usernameToNamespaceToAllowedPSPs[a.GetUser().GetName()][""][a.GetName()]
  81. allowedAPIGroup := len(t.allowedAPIGroupName) == 0 || a.GetAPIGroup() == t.allowedAPIGroupName
  82. if allowedAPIGroup && (allowedInNamespace || allowedClusterWide) {
  83. return authorizer.DecisionAllow, "", nil
  84. }
  85. return authorizer.DecisionNoOpinion, "", nil
  86. }
  87. var _ authorizer.Authorizer = &TestAuthorizer{}
  88. func useInitContainers(pod *kapi.Pod) *kapi.Pod {
  89. pod.Spec.InitContainers = pod.Spec.Containers
  90. pod.Spec.Containers = []kapi.Container{}
  91. return pod
  92. }
  93. func TestAdmitSeccomp(t *testing.T) {
  94. containerName := "container"
  95. tests := map[string]struct {
  96. pspAnnotations map[string]string
  97. podAnnotations map[string]string
  98. shouldPassAdmit bool
  99. shouldPassValidate bool
  100. }{
  101. "no seccomp, no pod annotations": {
  102. pspAnnotations: nil,
  103. podAnnotations: nil,
  104. shouldPassAdmit: true,
  105. shouldPassValidate: true,
  106. },
  107. "no seccomp, pod annotations": {
  108. pspAnnotations: nil,
  109. podAnnotations: map[string]string{
  110. kapi.SeccompPodAnnotationKey: "foo",
  111. },
  112. shouldPassAdmit: false,
  113. shouldPassValidate: false,
  114. },
  115. "no seccomp, container annotations": {
  116. pspAnnotations: nil,
  117. podAnnotations: map[string]string{
  118. kapi.SeccompContainerAnnotationKeyPrefix + containerName: "foo",
  119. },
  120. shouldPassAdmit: false,
  121. shouldPassValidate: false,
  122. },
  123. "seccomp, allow any no pod annotation": {
  124. pspAnnotations: map[string]string{
  125. seccomp.AllowedProfilesAnnotationKey: seccomp.AllowAny,
  126. },
  127. podAnnotations: nil,
  128. shouldPassAdmit: true,
  129. shouldPassValidate: true,
  130. },
  131. "seccomp, allow any pod annotation": {
  132. pspAnnotations: map[string]string{
  133. seccomp.AllowedProfilesAnnotationKey: seccomp.AllowAny,
  134. },
  135. podAnnotations: map[string]string{
  136. kapi.SeccompPodAnnotationKey: "foo",
  137. },
  138. shouldPassAdmit: true,
  139. shouldPassValidate: true,
  140. },
  141. "seccomp, allow any container annotation": {
  142. pspAnnotations: map[string]string{
  143. seccomp.AllowedProfilesAnnotationKey: seccomp.AllowAny,
  144. },
  145. podAnnotations: map[string]string{
  146. kapi.SeccompContainerAnnotationKeyPrefix + containerName: "foo",
  147. },
  148. shouldPassAdmit: true,
  149. shouldPassValidate: true,
  150. },
  151. "seccomp, allow specific pod annotation failure": {
  152. pspAnnotations: map[string]string{
  153. seccomp.AllowedProfilesAnnotationKey: "foo",
  154. },
  155. podAnnotations: map[string]string{
  156. kapi.SeccompPodAnnotationKey: "bar",
  157. },
  158. shouldPassAdmit: false,
  159. shouldPassValidate: false,
  160. },
  161. "seccomp, allow specific container annotation failure": {
  162. pspAnnotations: map[string]string{
  163. // provide a default so we don't have to give the pod annotation
  164. seccomp.DefaultProfileAnnotationKey: "foo",
  165. seccomp.AllowedProfilesAnnotationKey: "foo",
  166. },
  167. podAnnotations: map[string]string{
  168. kapi.SeccompContainerAnnotationKeyPrefix + containerName: "bar",
  169. },
  170. shouldPassAdmit: false,
  171. shouldPassValidate: false,
  172. },
  173. "seccomp, allow specific pod annotation pass": {
  174. pspAnnotations: map[string]string{
  175. seccomp.AllowedProfilesAnnotationKey: "foo",
  176. },
  177. podAnnotations: map[string]string{
  178. kapi.SeccompPodAnnotationKey: "foo",
  179. },
  180. shouldPassAdmit: true,
  181. shouldPassValidate: true,
  182. },
  183. "seccomp, allow specific container annotation pass": {
  184. pspAnnotations: map[string]string{
  185. // provide a default so we don't have to give the pod annotation
  186. seccomp.DefaultProfileAnnotationKey: "foo",
  187. seccomp.AllowedProfilesAnnotationKey: "foo,bar",
  188. },
  189. podAnnotations: map[string]string{
  190. kapi.SeccompContainerAnnotationKeyPrefix + containerName: "bar",
  191. },
  192. shouldPassAdmit: true,
  193. shouldPassValidate: true,
  194. },
  195. }
  196. for k, v := range tests {
  197. psp := restrictivePSP()
  198. psp.Annotations = v.pspAnnotations
  199. pod := &kapi.Pod{
  200. ObjectMeta: metav1.ObjectMeta{
  201. Annotations: v.podAnnotations,
  202. },
  203. Spec: kapi.PodSpec{
  204. Containers: []kapi.Container{
  205. {Name: containerName},
  206. },
  207. },
  208. }
  209. testPSPAdmit(k, []*policy.PodSecurityPolicy{psp}, pod, v.shouldPassAdmit, v.shouldPassValidate, psp.Name, t)
  210. }
  211. }
  212. func TestAdmitPrivileged(t *testing.T) {
  213. createPodWithPriv := func(priv bool) *kapi.Pod {
  214. pod := goodPod()
  215. pod.Spec.Containers[0].SecurityContext.Privileged = &priv
  216. return pod
  217. }
  218. nonPrivilegedPSP := restrictivePSP()
  219. nonPrivilegedPSP.Name = "non-priv"
  220. nonPrivilegedPSP.Spec.Privileged = false
  221. privilegedPSP := restrictivePSP()
  222. privilegedPSP.Name = "priv"
  223. privilegedPSP.Spec.Privileged = true
  224. trueValue := true
  225. falseValue := false
  226. tests := map[string]struct {
  227. pod *kapi.Pod
  228. psps []*policy.PodSecurityPolicy
  229. shouldPassAdmit bool
  230. shouldPassValidate bool
  231. expectedPriv *bool
  232. expectedPSP string
  233. }{
  234. "pod with priv=nil allowed under non priv PSP": {
  235. pod: goodPod(),
  236. psps: []*policy.PodSecurityPolicy{nonPrivilegedPSP},
  237. shouldPassAdmit: true,
  238. shouldPassValidate: true,
  239. expectedPriv: nil,
  240. expectedPSP: nonPrivilegedPSP.Name,
  241. },
  242. "pod with priv=nil allowed under priv PSP": {
  243. pod: goodPod(),
  244. psps: []*policy.PodSecurityPolicy{privilegedPSP},
  245. shouldPassAdmit: true,
  246. shouldPassValidate: true,
  247. expectedPriv: nil,
  248. expectedPSP: privilegedPSP.Name,
  249. },
  250. "pod with priv=false allowed under non priv PSP": {
  251. pod: createPodWithPriv(false),
  252. psps: []*policy.PodSecurityPolicy{nonPrivilegedPSP},
  253. shouldPassAdmit: true,
  254. shouldPassValidate: true,
  255. expectedPriv: &falseValue,
  256. expectedPSP: nonPrivilegedPSP.Name,
  257. },
  258. "pod with priv=false allowed under priv PSP": {
  259. pod: createPodWithPriv(false),
  260. psps: []*policy.PodSecurityPolicy{privilegedPSP},
  261. shouldPassAdmit: true,
  262. shouldPassValidate: true,
  263. expectedPriv: &falseValue,
  264. expectedPSP: privilegedPSP.Name,
  265. },
  266. "pod with priv=true denied by non priv PSP": {
  267. pod: createPodWithPriv(true),
  268. psps: []*policy.PodSecurityPolicy{nonPrivilegedPSP},
  269. shouldPassAdmit: false,
  270. shouldPassValidate: false,
  271. },
  272. "pod with priv=true allowed by priv PSP": {
  273. pod: createPodWithPriv(true),
  274. psps: []*policy.PodSecurityPolicy{nonPrivilegedPSP, privilegedPSP},
  275. shouldPassAdmit: true,
  276. shouldPassValidate: true,
  277. expectedPriv: &trueValue,
  278. expectedPSP: privilegedPSP.Name,
  279. },
  280. }
  281. for k, v := range tests {
  282. testPSPAdmit(k, v.psps, v.pod, v.shouldPassAdmit, v.shouldPassValidate, v.expectedPSP, t)
  283. if v.shouldPassAdmit {
  284. priv := v.pod.Spec.Containers[0].SecurityContext.Privileged
  285. if (priv == nil) != (v.expectedPriv == nil) {
  286. t.Errorf("%s expected privileged to be %v, got %v", k, v.expectedPriv, priv)
  287. } else if priv != nil && *priv != *v.expectedPriv {
  288. t.Errorf("%s expected privileged to be %v, got %v", k, *v.expectedPriv, *priv)
  289. }
  290. }
  291. }
  292. }
  293. func defaultPod(t *testing.T, pod *kapi.Pod) *kapi.Pod {
  294. v1Pod := &v1.Pod{}
  295. if err := legacyscheme.Scheme.Convert(pod, v1Pod, nil); err != nil {
  296. t.Fatal(err)
  297. }
  298. legacyscheme.Scheme.Default(v1Pod)
  299. apiPod := &kapi.Pod{}
  300. if err := legacyscheme.Scheme.Convert(v1Pod, apiPod, nil); err != nil {
  301. t.Fatal(err)
  302. }
  303. return apiPod
  304. }
  305. func TestAdmitPreferNonmutating(t *testing.T) {
  306. mutating1 := restrictivePSP()
  307. mutating1.Name = "mutating1"
  308. mutating1.Spec.RunAsUser.Ranges = []policy.IDRange{{Min: int64(1), Max: int64(1)}}
  309. mutating2 := restrictivePSP()
  310. mutating2.Name = "mutating2"
  311. mutating2.Spec.RunAsUser.Ranges = []policy.IDRange{{Min: int64(2), Max: int64(2)}}
  312. privilegedPSP := permissivePSP()
  313. privilegedPSP.Name = "privileged"
  314. unprivilegedRunAsAnyPod := defaultPod(t, &kapi.Pod{
  315. ObjectMeta: metav1.ObjectMeta{},
  316. Spec: kapi.PodSpec{
  317. ServiceAccountName: "default",
  318. Containers: []kapi.Container{{Name: "mycontainer", Image: "myimage"}},
  319. },
  320. })
  321. changedPod := unprivilegedRunAsAnyPod.DeepCopy()
  322. changedPod.Spec.Containers[0].Image = "myimage2"
  323. podWithSC := unprivilegedRunAsAnyPod.DeepCopy()
  324. podWithSC.Annotations = map[string]string{psputil.ValidatedPSPAnnotation: privilegedPSP.Name}
  325. changedPodWithSC := changedPod.DeepCopy()
  326. changedPodWithSC.Annotations = map[string]string{psputil.ValidatedPSPAnnotation: privilegedPSP.Name}
  327. gcChangedPod := unprivilegedRunAsAnyPod.DeepCopy()
  328. gcChangedPod.OwnerReferences = []metav1.OwnerReference{{Kind: "Foo", Name: "bar"}}
  329. gcChangedPod.Finalizers = []string{"foo"}
  330. podWithAnnotation := unprivilegedRunAsAnyPod.DeepCopy()
  331. podWithAnnotation.ObjectMeta.Annotations = map[string]string{
  332. // "mutating2" is lexicographically behind "mutating1", so "mutating1" should be
  333. // chosen because it's the canonical PSP order.
  334. psputil.ValidatedPSPAnnotation: mutating2.Name,
  335. }
  336. tests := map[string]struct {
  337. operation kadmission.Operation
  338. pod *kapi.Pod
  339. podBeforeUpdate *kapi.Pod
  340. psps []*policy.PodSecurityPolicy
  341. shouldPassValidate bool
  342. expectMutation bool
  343. expectedContainerUser *int64
  344. expectedPSP string
  345. }{
  346. "pod should not be mutated by allow-all strategies": {
  347. operation: kadmission.Create,
  348. pod: unprivilegedRunAsAnyPod.DeepCopy(),
  349. psps: []*policy.PodSecurityPolicy{privilegedPSP},
  350. shouldPassValidate: true,
  351. expectMutation: false,
  352. expectedContainerUser: nil,
  353. expectedPSP: privilegedPSP.Name,
  354. },
  355. "pod should prefer non-mutating PSP on create": {
  356. operation: kadmission.Create,
  357. pod: unprivilegedRunAsAnyPod.DeepCopy(),
  358. psps: []*policy.PodSecurityPolicy{mutating2, mutating1, privilegedPSP},
  359. shouldPassValidate: true,
  360. expectMutation: false,
  361. expectedContainerUser: nil,
  362. expectedPSP: privilegedPSP.Name,
  363. },
  364. "pod should use deterministic mutating PSP on create": {
  365. operation: kadmission.Create,
  366. pod: unprivilegedRunAsAnyPod.DeepCopy(),
  367. psps: []*policy.PodSecurityPolicy{mutating2, mutating1},
  368. shouldPassValidate: true,
  369. expectMutation: true,
  370. expectedContainerUser: &mutating1.Spec.RunAsUser.Ranges[0].Min,
  371. expectedPSP: mutating1.Name,
  372. },
  373. "pod should use deterministic mutating PSP on create even if ValidatedPSPAnnotation is set": {
  374. operation: kadmission.Create,
  375. pod: podWithAnnotation,
  376. psps: []*policy.PodSecurityPolicy{mutating2, mutating1},
  377. shouldPassValidate: true,
  378. expectMutation: true,
  379. expectedContainerUser: &mutating1.Spec.RunAsUser.Ranges[0].Min,
  380. expectedPSP: mutating1.Name,
  381. },
  382. "pod should prefer non-mutating PSP on update": {
  383. operation: kadmission.Update,
  384. pod: changedPodWithSC.DeepCopy(),
  385. podBeforeUpdate: podWithSC.DeepCopy(),
  386. psps: []*policy.PodSecurityPolicy{mutating2, mutating1, privilegedPSP},
  387. shouldPassValidate: true,
  388. expectMutation: false,
  389. expectedContainerUser: nil,
  390. expectedPSP: privilegedPSP.Name,
  391. },
  392. "pod should not mutate on update, but fail validation": {
  393. operation: kadmission.Update,
  394. pod: changedPod.DeepCopy(),
  395. podBeforeUpdate: unprivilegedRunAsAnyPod.DeepCopy(),
  396. psps: []*policy.PodSecurityPolicy{mutating2, mutating1},
  397. shouldPassValidate: false,
  398. expectMutation: false,
  399. expectedContainerUser: nil,
  400. expectedPSP: "",
  401. },
  402. "pod should be allowed if completely unchanged on update": {
  403. operation: kadmission.Update,
  404. pod: unprivilegedRunAsAnyPod.DeepCopy(),
  405. podBeforeUpdate: unprivilegedRunAsAnyPod.DeepCopy(),
  406. psps: []*policy.PodSecurityPolicy{mutating2, mutating1},
  407. shouldPassValidate: true,
  408. expectMutation: false,
  409. expectedContainerUser: nil,
  410. expectedPSP: "",
  411. },
  412. "pod should be allowed if unchanged on update except finalizers,ownerrefs": {
  413. operation: kadmission.Update,
  414. pod: gcChangedPod.DeepCopy(),
  415. podBeforeUpdate: unprivilegedRunAsAnyPod.DeepCopy(),
  416. psps: []*policy.PodSecurityPolicy{mutating2, mutating1},
  417. shouldPassValidate: true,
  418. expectMutation: false,
  419. expectedContainerUser: nil,
  420. expectedPSP: "",
  421. },
  422. }
  423. for k, v := range tests {
  424. testPSPAdmitAdvanced(k, v.operation, v.psps, nil, &user.DefaultInfo{}, v.pod, v.podBeforeUpdate, true, v.shouldPassValidate, v.expectMutation, v.expectedPSP, t)
  425. actualPodUser := (*int64)(nil)
  426. if v.pod.Spec.SecurityContext != nil {
  427. actualPodUser = v.pod.Spec.SecurityContext.RunAsUser
  428. }
  429. if actualPodUser != nil {
  430. t.Errorf("%s expected pod user nil, got %v", k, *actualPodUser)
  431. }
  432. actualContainerUser := (*int64)(nil)
  433. if v.pod.Spec.Containers[0].SecurityContext != nil {
  434. actualContainerUser = v.pod.Spec.Containers[0].SecurityContext.RunAsUser
  435. }
  436. if (actualContainerUser == nil) != (v.expectedContainerUser == nil) {
  437. t.Errorf("%s expected container user %v, got %v", k, v.expectedContainerUser, actualContainerUser)
  438. } else if actualContainerUser != nil && *actualContainerUser != *v.expectedContainerUser {
  439. t.Errorf("%s expected container user %v, got %v", k, *v.expectedContainerUser, *actualContainerUser)
  440. }
  441. }
  442. }
  443. func TestFailClosedOnInvalidPod(t *testing.T) {
  444. plugin := NewTestAdmission(nil, nil)
  445. pod := &v1.Pod{}
  446. attrs := kadmission.NewAttributesRecord(pod, nil, kapi.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, kapi.Resource("pods").WithVersion("version"), "", kadmission.Create, &metav1.CreateOptions{}, false, &user.DefaultInfo{})
  447. err := plugin.Admit(attrs, nil)
  448. if err == nil {
  449. t.Fatalf("expected versioned pod object to fail mutating admission")
  450. }
  451. if !strings.Contains(err.Error(), "unexpected type") {
  452. t.Errorf("expected type error on Admit but got: %v", err)
  453. }
  454. err = plugin.Validate(attrs, nil)
  455. if err == nil {
  456. t.Fatalf("expected versioned pod object to fail validating admission")
  457. }
  458. if !strings.Contains(err.Error(), "unexpected type") {
  459. t.Errorf("expected type error on Validate but got: %v", err)
  460. }
  461. }
  462. func TestAdmitCaps(t *testing.T) {
  463. createPodWithCaps := func(caps *kapi.Capabilities) *kapi.Pod {
  464. pod := goodPod()
  465. pod.Spec.Containers[0].SecurityContext.Capabilities = caps
  466. return pod
  467. }
  468. restricted := restrictivePSP()
  469. allowsFooInAllowed := restrictivePSP()
  470. allowsFooInAllowed.Name = "allowCapInAllowed"
  471. allowsFooInAllowed.Spec.AllowedCapabilities = []v1.Capability{"foo"}
  472. allowsFooInRequired := restrictivePSP()
  473. allowsFooInRequired.Name = "allowCapInRequired"
  474. allowsFooInRequired.Spec.DefaultAddCapabilities = []v1.Capability{"foo"}
  475. requiresFooToBeDropped := restrictivePSP()
  476. requiresFooToBeDropped.Name = "requireDrop"
  477. requiresFooToBeDropped.Spec.RequiredDropCapabilities = []v1.Capability{"foo"}
  478. allowAllInAllowed := restrictivePSP()
  479. allowAllInAllowed.Name = "allowAllCapsInAllowed"
  480. allowAllInAllowed.Spec.AllowedCapabilities = []v1.Capability{policy.AllowAllCapabilities}
  481. tc := map[string]struct {
  482. pod *kapi.Pod
  483. psps []*policy.PodSecurityPolicy
  484. shouldPassAdmit bool
  485. shouldPassValidate bool
  486. expectedCapabilities *kapi.Capabilities
  487. expectedPSP string
  488. }{
  489. // UC 1: if a PSP does not define allowed or required caps then a pod requesting a cap
  490. // should be rejected.
  491. "should reject cap add when not allowed or required": {
  492. pod: createPodWithCaps(&kapi.Capabilities{Add: []kapi.Capability{"foo"}}),
  493. psps: []*policy.PodSecurityPolicy{restricted},
  494. shouldPassAdmit: false,
  495. shouldPassValidate: false,
  496. },
  497. // UC 2: if a PSP allows a cap in the allowed field it should accept the pod request
  498. // to add the cap.
  499. "should accept cap add when in allowed": {
  500. pod: createPodWithCaps(&kapi.Capabilities{Add: []kapi.Capability{"foo"}}),
  501. psps: []*policy.PodSecurityPolicy{restricted, allowsFooInAllowed},
  502. shouldPassAdmit: true,
  503. shouldPassValidate: true,
  504. expectedPSP: allowsFooInAllowed.Name,
  505. },
  506. // UC 3: if a PSP requires a cap then it should accept the pod request
  507. // to add the cap.
  508. "should accept cap add when in required": {
  509. pod: createPodWithCaps(&kapi.Capabilities{Add: []kapi.Capability{"foo"}}),
  510. psps: []*policy.PodSecurityPolicy{restricted, allowsFooInRequired},
  511. shouldPassAdmit: true,
  512. shouldPassValidate: true,
  513. expectedPSP: allowsFooInRequired.Name,
  514. },
  515. // UC 4: if a PSP requires a cap to be dropped then it should fail both
  516. // in the verification of adds and verification of drops
  517. "should reject cap add when requested cap is required to be dropped": {
  518. pod: createPodWithCaps(&kapi.Capabilities{Add: []kapi.Capability{"foo"}}),
  519. psps: []*policy.PodSecurityPolicy{restricted, requiresFooToBeDropped},
  520. shouldPassAdmit: false,
  521. shouldPassValidate: false,
  522. },
  523. // UC 5: if a PSP requires a cap to be dropped it should accept
  524. // a manual request to drop the cap.
  525. "should accept cap drop when cap is required to be dropped": {
  526. pod: createPodWithCaps(&kapi.Capabilities{Drop: []kapi.Capability{"foo"}}),
  527. psps: []*policy.PodSecurityPolicy{requiresFooToBeDropped},
  528. shouldPassAdmit: true,
  529. shouldPassValidate: true,
  530. expectedPSP: requiresFooToBeDropped.Name,
  531. },
  532. // UC 6: required add is defaulted
  533. "required add is defaulted": {
  534. pod: goodPod(),
  535. psps: []*policy.PodSecurityPolicy{allowsFooInRequired},
  536. shouldPassAdmit: true,
  537. shouldPassValidate: true,
  538. expectedCapabilities: &kapi.Capabilities{
  539. Add: []kapi.Capability{"foo"},
  540. },
  541. expectedPSP: allowsFooInRequired.Name,
  542. },
  543. // UC 7: required drop is defaulted
  544. "required drop is defaulted": {
  545. pod: goodPod(),
  546. psps: []*policy.PodSecurityPolicy{requiresFooToBeDropped},
  547. shouldPassAdmit: true,
  548. shouldPassValidate: true,
  549. expectedCapabilities: &kapi.Capabilities{
  550. Drop: []kapi.Capability{"foo"},
  551. },
  552. expectedPSP: requiresFooToBeDropped.Name,
  553. },
  554. // UC 8: using '*' in allowed caps
  555. "should accept cap add when all caps are allowed": {
  556. pod: createPodWithCaps(&kapi.Capabilities{Add: []kapi.Capability{"foo"}}),
  557. psps: []*policy.PodSecurityPolicy{restricted, allowAllInAllowed},
  558. shouldPassAdmit: true,
  559. shouldPassValidate: true,
  560. expectedPSP: allowAllInAllowed.Name,
  561. },
  562. }
  563. for k, v := range tc {
  564. testPSPAdmit(k, v.psps, v.pod, v.shouldPassAdmit, v.shouldPassValidate, v.expectedPSP, t)
  565. if v.expectedCapabilities != nil {
  566. if !reflect.DeepEqual(v.expectedCapabilities, v.pod.Spec.Containers[0].SecurityContext.Capabilities) {
  567. t.Errorf("%s resulted in caps that were not expected - expected: %v, received: %v", k, v.expectedCapabilities, v.pod.Spec.Containers[0].SecurityContext.Capabilities)
  568. }
  569. }
  570. }
  571. for k, v := range tc {
  572. useInitContainers(v.pod)
  573. testPSPAdmit(k, v.psps, v.pod, v.shouldPassAdmit, v.shouldPassValidate, v.expectedPSP, t)
  574. if v.expectedCapabilities != nil {
  575. if !reflect.DeepEqual(v.expectedCapabilities, v.pod.Spec.InitContainers[0].SecurityContext.Capabilities) {
  576. t.Errorf("%s resulted in caps that were not expected - expected: %v, received: %v", k, v.expectedCapabilities, v.pod.Spec.InitContainers[0].SecurityContext.Capabilities)
  577. }
  578. }
  579. }
  580. }
  581. func TestAdmitVolumes(t *testing.T) {
  582. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.CSIInlineVolume, true)()
  583. val := reflect.ValueOf(kapi.VolumeSource{})
  584. for i := 0; i < val.NumField(); i++ {
  585. // reflectively create the volume source
  586. fieldVal := val.Type().Field(i)
  587. volumeSource := kapi.VolumeSource{}
  588. volumeSourceVolume := reflect.New(fieldVal.Type.Elem())
  589. reflect.ValueOf(&volumeSource).Elem().FieldByName(fieldVal.Name).Set(volumeSourceVolume)
  590. volume := kapi.Volume{VolumeSource: volumeSource}
  591. // sanity check before moving on
  592. fsType, err := psputil.GetVolumeFSType(volume)
  593. if err != nil {
  594. t.Errorf("error getting FSType for %s: %s", fieldVal.Name, err.Error())
  595. continue
  596. }
  597. // add the volume to the pod
  598. pod := goodPod()
  599. pod.Spec.Volumes = []kapi.Volume{volume}
  600. // create a PSP that allows no volumes
  601. psp := restrictivePSP()
  602. // expect a denial for this PSP
  603. testPSPAdmit(fmt.Sprintf("%s denial", string(fsType)), []*policy.PodSecurityPolicy{psp}, pod, false, false, "", t)
  604. // also expect a denial for this PSP if it's an init container
  605. useInitContainers(pod)
  606. testPSPAdmit(fmt.Sprintf("%s denial", string(fsType)), []*policy.PodSecurityPolicy{psp}, pod, false, false, "", t)
  607. // now add the fstype directly to the psp and it should validate
  608. psp.Spec.Volumes = []policy.FSType{fsType}
  609. testPSPAdmit(fmt.Sprintf("%s direct accept", string(fsType)), []*policy.PodSecurityPolicy{psp}, pod, true, true, psp.Name, t)
  610. // now change the psp to allow any volumes and the pod should still validate
  611. psp.Spec.Volumes = []policy.FSType{policy.All}
  612. testPSPAdmit(fmt.Sprintf("%s wildcard accept", string(fsType)), []*policy.PodSecurityPolicy{psp}, pod, true, true, psp.Name, t)
  613. }
  614. }
  615. func TestAdmitHostNetwork(t *testing.T) {
  616. createPodWithHostNetwork := func(hostNetwork bool) *kapi.Pod {
  617. pod := goodPod()
  618. pod.Spec.SecurityContext.HostNetwork = hostNetwork
  619. return pod
  620. }
  621. noHostNetwork := restrictivePSP()
  622. noHostNetwork.Name = "no-hostnetwork"
  623. noHostNetwork.Spec.HostNetwork = false
  624. hostNetwork := restrictivePSP()
  625. hostNetwork.Name = "hostnetwork"
  626. hostNetwork.Spec.HostNetwork = true
  627. tests := map[string]struct {
  628. pod *kapi.Pod
  629. psps []*policy.PodSecurityPolicy
  630. shouldPassAdmit bool
  631. shouldPassValidate bool
  632. expectedHostNetwork bool
  633. expectedPSP string
  634. }{
  635. "pod without hostnetwork request allowed under noHostNetwork PSP": {
  636. pod: goodPod(),
  637. psps: []*policy.PodSecurityPolicy{noHostNetwork},
  638. shouldPassAdmit: true,
  639. shouldPassValidate: true,
  640. expectedHostNetwork: false,
  641. expectedPSP: noHostNetwork.Name,
  642. },
  643. "pod without hostnetwork request allowed under hostNetwork PSP": {
  644. pod: goodPod(),
  645. psps: []*policy.PodSecurityPolicy{hostNetwork},
  646. shouldPassAdmit: true,
  647. shouldPassValidate: true,
  648. expectedHostNetwork: false,
  649. expectedPSP: hostNetwork.Name,
  650. },
  651. "pod with hostnetwork request denied by noHostNetwork PSP": {
  652. pod: createPodWithHostNetwork(true),
  653. psps: []*policy.PodSecurityPolicy{noHostNetwork},
  654. shouldPassAdmit: false,
  655. shouldPassValidate: false,
  656. },
  657. "pod with hostnetwork request allowed by hostNetwork PSP": {
  658. pod: createPodWithHostNetwork(true),
  659. psps: []*policy.PodSecurityPolicy{noHostNetwork, hostNetwork},
  660. shouldPassAdmit: true,
  661. shouldPassValidate: true,
  662. expectedHostNetwork: true,
  663. expectedPSP: hostNetwork.Name,
  664. },
  665. }
  666. for k, v := range tests {
  667. testPSPAdmit(k, v.psps, v.pod, v.shouldPassAdmit, v.shouldPassValidate, v.expectedPSP, t)
  668. if v.shouldPassAdmit {
  669. if v.pod.Spec.SecurityContext.HostNetwork != v.expectedHostNetwork {
  670. t.Errorf("%s expected hostNetwork to be %t", k, v.expectedHostNetwork)
  671. }
  672. }
  673. }
  674. // test again with init containers
  675. for k, v := range tests {
  676. useInitContainers(v.pod)
  677. testPSPAdmit(k, v.psps, v.pod, v.shouldPassAdmit, v.shouldPassValidate, v.expectedPSP, t)
  678. if v.shouldPassAdmit {
  679. if v.pod.Spec.SecurityContext.HostNetwork != v.expectedHostNetwork {
  680. t.Errorf("%s expected hostNetwork to be %t", k, v.expectedHostNetwork)
  681. }
  682. }
  683. }
  684. }
  685. func TestAdmitHostPorts(t *testing.T) {
  686. createPodWithHostPorts := func(port int32) *kapi.Pod {
  687. pod := goodPod()
  688. pod.Spec.Containers[0].Ports = []kapi.ContainerPort{
  689. {HostPort: port},
  690. }
  691. return pod
  692. }
  693. noHostPorts := restrictivePSP()
  694. noHostPorts.Name = "noHostPorts"
  695. hostPorts := restrictivePSP()
  696. hostPorts.Name = "hostPorts"
  697. hostPorts.Spec.HostPorts = []policy.HostPortRange{
  698. {Min: 1, Max: 10},
  699. }
  700. tests := map[string]struct {
  701. pod *kapi.Pod
  702. psps []*policy.PodSecurityPolicy
  703. shouldPassAdmit bool
  704. shouldPassValidate bool
  705. expectedPSP string
  706. }{
  707. "host port out of range": {
  708. pod: createPodWithHostPorts(11),
  709. psps: []*policy.PodSecurityPolicy{hostPorts},
  710. shouldPassAdmit: false,
  711. shouldPassValidate: false,
  712. },
  713. "host port in range": {
  714. pod: createPodWithHostPorts(5),
  715. psps: []*policy.PodSecurityPolicy{hostPorts},
  716. shouldPassAdmit: true,
  717. shouldPassValidate: true,
  718. expectedPSP: hostPorts.Name,
  719. },
  720. "no host ports with range": {
  721. pod: goodPod(),
  722. psps: []*policy.PodSecurityPolicy{hostPorts},
  723. shouldPassAdmit: true,
  724. shouldPassValidate: true,
  725. expectedPSP: hostPorts.Name,
  726. },
  727. "no host ports without range": {
  728. pod: goodPod(),
  729. psps: []*policy.PodSecurityPolicy{noHostPorts},
  730. shouldPassAdmit: true,
  731. shouldPassValidate: true,
  732. expectedPSP: noHostPorts.Name,
  733. },
  734. "host ports without range": {
  735. pod: createPodWithHostPorts(5),
  736. psps: []*policy.PodSecurityPolicy{noHostPorts},
  737. shouldPassAdmit: false,
  738. shouldPassValidate: false,
  739. },
  740. }
  741. for i := 0; i < 2; i++ {
  742. for k, v := range tests {
  743. v.pod.Spec.Containers, v.pod.Spec.InitContainers = v.pod.Spec.InitContainers, v.pod.Spec.Containers
  744. testPSPAdmit(k, v.psps, v.pod, v.shouldPassAdmit, v.shouldPassValidate, v.expectedPSP, t)
  745. }
  746. }
  747. }
  748. func TestAdmitHostPID(t *testing.T) {
  749. createPodWithHostPID := func(hostPID bool) *kapi.Pod {
  750. pod := goodPod()
  751. pod.Spec.SecurityContext.HostPID = hostPID
  752. return pod
  753. }
  754. noHostPID := restrictivePSP()
  755. noHostPID.Name = "no-hostpid"
  756. noHostPID.Spec.HostPID = false
  757. hostPID := restrictivePSP()
  758. hostPID.Name = "hostpid"
  759. hostPID.Spec.HostPID = true
  760. tests := map[string]struct {
  761. pod *kapi.Pod
  762. psps []*policy.PodSecurityPolicy
  763. shouldPassAdmit bool
  764. shouldPassValidate bool
  765. expectedHostPID bool
  766. expectedPSP string
  767. }{
  768. "pod without hostpid request allowed under noHostPID PSP": {
  769. pod: goodPod(),
  770. psps: []*policy.PodSecurityPolicy{noHostPID},
  771. shouldPassAdmit: true,
  772. shouldPassValidate: true,
  773. expectedHostPID: false,
  774. expectedPSP: noHostPID.Name,
  775. },
  776. "pod without hostpid request allowed under hostPID PSP": {
  777. pod: goodPod(),
  778. psps: []*policy.PodSecurityPolicy{hostPID},
  779. shouldPassAdmit: true,
  780. shouldPassValidate: true,
  781. expectedHostPID: false,
  782. expectedPSP: hostPID.Name,
  783. },
  784. "pod with hostpid request denied by noHostPID PSP": {
  785. pod: createPodWithHostPID(true),
  786. psps: []*policy.PodSecurityPolicy{noHostPID},
  787. shouldPassAdmit: false,
  788. },
  789. "pod with hostpid request allowed by hostPID PSP": {
  790. pod: createPodWithHostPID(true),
  791. psps: []*policy.PodSecurityPolicy{noHostPID, hostPID},
  792. shouldPassAdmit: true,
  793. shouldPassValidate: true,
  794. expectedHostPID: true,
  795. expectedPSP: hostPID.Name,
  796. },
  797. }
  798. for k, v := range tests {
  799. testPSPAdmit(k, v.psps, v.pod, v.shouldPassAdmit, v.shouldPassValidate, v.expectedPSP, t)
  800. if v.shouldPassAdmit {
  801. if v.pod.Spec.SecurityContext.HostPID != v.expectedHostPID {
  802. t.Errorf("%s expected hostPID to be %t", k, v.expectedHostPID)
  803. }
  804. }
  805. }
  806. }
  807. func TestAdmitHostIPC(t *testing.T) {
  808. createPodWithHostIPC := func(hostIPC bool) *kapi.Pod {
  809. pod := goodPod()
  810. pod.Spec.SecurityContext.HostIPC = hostIPC
  811. return pod
  812. }
  813. noHostIPC := restrictivePSP()
  814. noHostIPC.Name = "no-hostIPC"
  815. noHostIPC.Spec.HostIPC = false
  816. hostIPC := restrictivePSP()
  817. hostIPC.Name = "hostIPC"
  818. hostIPC.Spec.HostIPC = true
  819. tests := map[string]struct {
  820. pod *kapi.Pod
  821. psps []*policy.PodSecurityPolicy
  822. shouldPassAdmit bool
  823. shouldPassValidate bool
  824. expectedHostIPC bool
  825. expectedPSP string
  826. }{
  827. "pod without hostIPC request allowed under noHostIPC PSP": {
  828. pod: goodPod(),
  829. psps: []*policy.PodSecurityPolicy{noHostIPC},
  830. shouldPassAdmit: true,
  831. shouldPassValidate: true,
  832. expectedHostIPC: false,
  833. expectedPSP: noHostIPC.Name,
  834. },
  835. "pod without hostIPC request allowed under hostIPC PSP": {
  836. pod: goodPod(),
  837. psps: []*policy.PodSecurityPolicy{hostIPC},
  838. shouldPassAdmit: true,
  839. shouldPassValidate: true,
  840. expectedHostIPC: false,
  841. expectedPSP: hostIPC.Name,
  842. },
  843. "pod with hostIPC request denied by noHostIPC PSP": {
  844. pod: createPodWithHostIPC(true),
  845. psps: []*policy.PodSecurityPolicy{noHostIPC},
  846. shouldPassAdmit: false,
  847. shouldPassValidate: false,
  848. },
  849. "pod with hostIPC request allowed by hostIPC PSP": {
  850. pod: createPodWithHostIPC(true),
  851. psps: []*policy.PodSecurityPolicy{noHostIPC, hostIPC},
  852. shouldPassAdmit: true,
  853. shouldPassValidate: true,
  854. expectedHostIPC: true,
  855. expectedPSP: hostIPC.Name,
  856. },
  857. }
  858. for k, v := range tests {
  859. testPSPAdmit(k, v.psps, v.pod, v.shouldPassAdmit, v.shouldPassValidate, v.expectedPSP, t)
  860. if v.shouldPassAdmit {
  861. if v.pod.Spec.SecurityContext.HostIPC != v.expectedHostIPC {
  862. t.Errorf("%s expected hostIPC to be %t", k, v.expectedHostIPC)
  863. }
  864. }
  865. }
  866. }
  867. func createPodWithSecurityContexts(podSC *kapi.PodSecurityContext, containerSC *kapi.SecurityContext) *kapi.Pod {
  868. pod := goodPod()
  869. pod.Spec.SecurityContext = podSC
  870. pod.Spec.Containers[0].SecurityContext = containerSC
  871. return pod
  872. }
  873. func TestAdmitSELinux(t *testing.T) {
  874. runAsAny := permissivePSP()
  875. runAsAny.Name = "runAsAny"
  876. runAsAny.Spec.SELinux.Rule = policy.SELinuxStrategyRunAsAny
  877. runAsAny.Spec.SELinux.SELinuxOptions = nil
  878. mustRunAs := permissivePSP()
  879. mustRunAs.Name = "mustRunAs"
  880. mustRunAs.Spec.SELinux.Rule = policy.SELinuxStrategyMustRunAs
  881. mustRunAs.Spec.SELinux.SELinuxOptions = &v1.SELinuxOptions{}
  882. mustRunAs.Spec.SELinux.SELinuxOptions.Level = "level"
  883. mustRunAs.Spec.SELinux.SELinuxOptions.Role = "role"
  884. mustRunAs.Spec.SELinux.SELinuxOptions.Type = "type"
  885. mustRunAs.Spec.SELinux.SELinuxOptions.User = "user"
  886. getInternalSEOptions := func(policy *policy.PodSecurityPolicy) *kapi.SELinuxOptions {
  887. opt := kapi.SELinuxOptions{}
  888. k8s_api_v1.Convert_v1_SELinuxOptions_To_core_SELinuxOptions(policy.Spec.SELinux.SELinuxOptions, &opt, nil)
  889. return &opt
  890. }
  891. tests := map[string]struct {
  892. pod *kapi.Pod
  893. psps []*policy.PodSecurityPolicy
  894. shouldPassAdmit bool
  895. shouldPassValidate bool
  896. expectedPodSC *kapi.PodSecurityContext
  897. expectedContainerSC *kapi.SecurityContext
  898. expectedPSP string
  899. }{
  900. "runAsAny with no request": {
  901. pod: createPodWithSecurityContexts(nil, nil),
  902. psps: []*policy.PodSecurityPolicy{runAsAny},
  903. shouldPassAdmit: true,
  904. shouldPassValidate: true,
  905. expectedPodSC: nil,
  906. expectedContainerSC: nil,
  907. expectedPSP: runAsAny.Name,
  908. },
  909. "runAsAny with empty pod request": {
  910. pod: createPodWithSecurityContexts(&kapi.PodSecurityContext{}, nil),
  911. psps: []*policy.PodSecurityPolicy{runAsAny},
  912. shouldPassAdmit: true,
  913. shouldPassValidate: true,
  914. expectedPodSC: &kapi.PodSecurityContext{},
  915. expectedContainerSC: nil,
  916. expectedPSP: runAsAny.Name,
  917. },
  918. "runAsAny with empty container request": {
  919. pod: createPodWithSecurityContexts(nil, &kapi.SecurityContext{}),
  920. psps: []*policy.PodSecurityPolicy{runAsAny},
  921. shouldPassAdmit: true,
  922. shouldPassValidate: true,
  923. expectedPodSC: nil,
  924. expectedContainerSC: &kapi.SecurityContext{},
  925. expectedPSP: runAsAny.Name,
  926. },
  927. "runAsAny with pod request": {
  928. pod: createPodWithSecurityContexts(&kapi.PodSecurityContext{SELinuxOptions: &kapi.SELinuxOptions{User: "foo"}}, nil),
  929. psps: []*policy.PodSecurityPolicy{runAsAny},
  930. shouldPassAdmit: true,
  931. shouldPassValidate: true,
  932. expectedPodSC: &kapi.PodSecurityContext{SELinuxOptions: &kapi.SELinuxOptions{User: "foo"}},
  933. expectedContainerSC: nil,
  934. expectedPSP: runAsAny.Name,
  935. },
  936. "runAsAny with container request": {
  937. pod: createPodWithSecurityContexts(nil, &kapi.SecurityContext{SELinuxOptions: &kapi.SELinuxOptions{User: "foo"}}),
  938. psps: []*policy.PodSecurityPolicy{runAsAny},
  939. shouldPassAdmit: true,
  940. shouldPassValidate: true,
  941. expectedPodSC: nil,
  942. expectedContainerSC: &kapi.SecurityContext{SELinuxOptions: &kapi.SELinuxOptions{User: "foo"}},
  943. expectedPSP: runAsAny.Name,
  944. },
  945. "runAsAny with pod and container request": {
  946. pod: createPodWithSecurityContexts(&kapi.PodSecurityContext{SELinuxOptions: &kapi.SELinuxOptions{User: "bar"}}, &kapi.SecurityContext{SELinuxOptions: &kapi.SELinuxOptions{User: "foo"}}),
  947. psps: []*policy.PodSecurityPolicy{runAsAny},
  948. shouldPassAdmit: true,
  949. shouldPassValidate: true,
  950. expectedPodSC: &kapi.PodSecurityContext{SELinuxOptions: &kapi.SELinuxOptions{User: "bar"}},
  951. expectedContainerSC: &kapi.SecurityContext{SELinuxOptions: &kapi.SELinuxOptions{User: "foo"}},
  952. expectedPSP: runAsAny.Name,
  953. },
  954. "mustRunAs with bad pod request": {
  955. pod: createPodWithSecurityContexts(&kapi.PodSecurityContext{SELinuxOptions: &kapi.SELinuxOptions{User: "foo"}}, nil),
  956. psps: []*policy.PodSecurityPolicy{mustRunAs},
  957. shouldPassAdmit: false,
  958. shouldPassValidate: false,
  959. },
  960. "mustRunAs with bad container request": {
  961. pod: createPodWithSecurityContexts(nil, &kapi.SecurityContext{SELinuxOptions: &kapi.SELinuxOptions{User: "foo"}}),
  962. psps: []*policy.PodSecurityPolicy{mustRunAs},
  963. shouldPassAdmit: false,
  964. shouldPassValidate: false,
  965. },
  966. "mustRunAs with no request": {
  967. pod: createPodWithSecurityContexts(nil, nil),
  968. psps: []*policy.PodSecurityPolicy{mustRunAs},
  969. shouldPassAdmit: true,
  970. shouldPassValidate: true,
  971. expectedPodSC: &kapi.PodSecurityContext{SELinuxOptions: getInternalSEOptions(mustRunAs)},
  972. expectedContainerSC: nil,
  973. expectedPSP: mustRunAs.Name,
  974. },
  975. "mustRunAs with good pod request": {
  976. pod: createPodWithSecurityContexts(
  977. &kapi.PodSecurityContext{SELinuxOptions: &kapi.SELinuxOptions{Level: "level", Role: "role", Type: "type", User: "user"}},
  978. nil,
  979. ),
  980. psps: []*policy.PodSecurityPolicy{mustRunAs},
  981. shouldPassAdmit: true,
  982. shouldPassValidate: true,
  983. expectedPodSC: &kapi.PodSecurityContext{SELinuxOptions: getInternalSEOptions(mustRunAs)},
  984. expectedContainerSC: nil,
  985. expectedPSP: mustRunAs.Name,
  986. },
  987. "mustRunAs with good container request": {
  988. pod: createPodWithSecurityContexts(
  989. &kapi.PodSecurityContext{SELinuxOptions: &kapi.SELinuxOptions{Level: "level", Role: "role", Type: "type", User: "user"}},
  990. nil,
  991. ),
  992. psps: []*policy.PodSecurityPolicy{mustRunAs},
  993. shouldPassAdmit: true,
  994. shouldPassValidate: true,
  995. expectedPodSC: &kapi.PodSecurityContext{SELinuxOptions: getInternalSEOptions(mustRunAs)},
  996. expectedContainerSC: nil,
  997. expectedPSP: mustRunAs.Name,
  998. },
  999. }
  1000. for k, v := range tests {
  1001. testPSPAdmit(k, v.psps, v.pod, v.shouldPassAdmit, v.shouldPassValidate, v.expectedPSP, t)
  1002. if v.shouldPassAdmit {
  1003. if !reflect.DeepEqual(v.expectedPodSC, v.pod.Spec.SecurityContext) {
  1004. t.Errorf("%s unexpected diff:\n%s", k, diff.ObjectGoPrintSideBySide(v.expectedPodSC, v.pod.Spec.SecurityContext))
  1005. }
  1006. if !reflect.DeepEqual(v.expectedContainerSC, v.pod.Spec.Containers[0].SecurityContext) {
  1007. t.Errorf("%s unexpected diff:\n%s", k, diff.ObjectGoPrintSideBySide(v.expectedContainerSC, v.pod.Spec.Containers[0].SecurityContext))
  1008. }
  1009. }
  1010. }
  1011. }
  1012. func TestAdmitAppArmor(t *testing.T) {
  1013. createPodWithAppArmor := func(profile string) *kapi.Pod {
  1014. pod := goodPod()
  1015. apparmor.SetProfileNameFromPodAnnotations(pod.Annotations, defaultContainerName, profile)
  1016. return pod
  1017. }
  1018. unconstrainedPSP := restrictivePSP()
  1019. defaultedPSP := restrictivePSP()
  1020. defaultedPSP.Annotations = map[string]string{
  1021. apparmor.DefaultProfileAnnotationKey: apparmor.ProfileRuntimeDefault,
  1022. }
  1023. appArmorPSP := restrictivePSP()
  1024. appArmorPSP.Annotations = map[string]string{
  1025. apparmor.AllowedProfilesAnnotationKey: apparmor.ProfileRuntimeDefault,
  1026. }
  1027. appArmorDefaultPSP := restrictivePSP()
  1028. appArmorDefaultPSP.Annotations = map[string]string{
  1029. apparmor.DefaultProfileAnnotationKey: apparmor.ProfileRuntimeDefault,
  1030. apparmor.AllowedProfilesAnnotationKey: apparmor.ProfileRuntimeDefault + "," + apparmor.ProfileNamePrefix + "foo",
  1031. }
  1032. tests := map[string]struct {
  1033. pod *kapi.Pod
  1034. psp *policy.PodSecurityPolicy
  1035. shouldPassAdmit bool
  1036. shouldPassValidate bool
  1037. expectedProfile string
  1038. }{
  1039. "unconstrained with no profile": {
  1040. pod: goodPod(),
  1041. psp: unconstrainedPSP,
  1042. shouldPassAdmit: true,
  1043. shouldPassValidate: true,
  1044. expectedProfile: "",
  1045. },
  1046. "unconstrained with profile": {
  1047. pod: createPodWithAppArmor(apparmor.ProfileRuntimeDefault),
  1048. psp: unconstrainedPSP,
  1049. shouldPassAdmit: true,
  1050. shouldPassValidate: true,
  1051. expectedProfile: apparmor.ProfileRuntimeDefault,
  1052. },
  1053. "unconstrained with default profile": {
  1054. pod: goodPod(),
  1055. psp: defaultedPSP,
  1056. shouldPassAdmit: true,
  1057. shouldPassValidate: true,
  1058. expectedProfile: apparmor.ProfileRuntimeDefault,
  1059. },
  1060. "AppArmor enforced with no profile": {
  1061. pod: goodPod(),
  1062. psp: appArmorPSP,
  1063. shouldPassAdmit: false,
  1064. shouldPassValidate: false,
  1065. },
  1066. "AppArmor enforced with default profile": {
  1067. pod: goodPod(),
  1068. psp: appArmorDefaultPSP,
  1069. shouldPassAdmit: true,
  1070. shouldPassValidate: true,
  1071. expectedProfile: apparmor.ProfileRuntimeDefault,
  1072. },
  1073. "AppArmor enforced with good profile": {
  1074. pod: createPodWithAppArmor(apparmor.ProfileNamePrefix + "foo"),
  1075. psp: appArmorDefaultPSP,
  1076. shouldPassAdmit: true,
  1077. shouldPassValidate: true,
  1078. expectedProfile: apparmor.ProfileNamePrefix + "foo",
  1079. },
  1080. "AppArmor enforced with local profile": {
  1081. pod: createPodWithAppArmor(apparmor.ProfileNamePrefix + "bar"),
  1082. psp: appArmorPSP,
  1083. shouldPassAdmit: false,
  1084. shouldPassValidate: false,
  1085. },
  1086. }
  1087. for k, v := range tests {
  1088. testPSPAdmit(k, []*policy.PodSecurityPolicy{v.psp}, v.pod, v.shouldPassAdmit, v.shouldPassValidate, v.psp.Name, t)
  1089. if v.shouldPassAdmit {
  1090. assert.Equal(t, v.expectedProfile, apparmor.GetProfileNameFromPodAnnotations(v.pod.Annotations, defaultContainerName), k)
  1091. }
  1092. }
  1093. }
  1094. func TestAdmitRunAsUser(t *testing.T) {
  1095. podSC := func(user *int64) *kapi.PodSecurityContext {
  1096. return &kapi.PodSecurityContext{RunAsUser: user}
  1097. }
  1098. containerSC := func(user *int64) *kapi.SecurityContext {
  1099. return &kapi.SecurityContext{RunAsUser: user}
  1100. }
  1101. runAsAny := permissivePSP()
  1102. runAsAny.Name = "runAsAny"
  1103. runAsAny.Spec.RunAsUser.Rule = policy.RunAsUserStrategyRunAsAny
  1104. mustRunAs := permissivePSP()
  1105. mustRunAs.Name = "mustRunAs"
  1106. mustRunAs.Spec.RunAsUser.Rule = policy.RunAsUserStrategyMustRunAs
  1107. mustRunAs.Spec.RunAsUser.Ranges = []policy.IDRange{
  1108. {Min: int64(999), Max: int64(1000)},
  1109. }
  1110. runAsNonRoot := permissivePSP()
  1111. runAsNonRoot.Name = "runAsNonRoot"
  1112. runAsNonRoot.Spec.RunAsUser.Rule = policy.RunAsUserStrategyMustRunAsNonRoot
  1113. trueValue := true
  1114. tests := map[string]struct {
  1115. pod *kapi.Pod
  1116. psps []*policy.PodSecurityPolicy
  1117. shouldPassAdmit bool
  1118. shouldPassValidate bool
  1119. expectedPodSC *kapi.PodSecurityContext
  1120. expectedContainerSC *kapi.SecurityContext
  1121. expectedPSP string
  1122. }{
  1123. "runAsAny no pod request": {
  1124. pod: createPodWithSecurityContexts(nil, nil),
  1125. psps: []*policy.PodSecurityPolicy{runAsAny},
  1126. shouldPassAdmit: true,
  1127. shouldPassValidate: true,
  1128. expectedPodSC: nil,
  1129. expectedContainerSC: nil,
  1130. expectedPSP: runAsAny.Name,
  1131. },
  1132. "runAsAny pod request": {
  1133. pod: createPodWithSecurityContexts(podSC(utilpointer.Int64Ptr(1)), nil),
  1134. psps: []*policy.PodSecurityPolicy{runAsAny},
  1135. shouldPassAdmit: true,
  1136. shouldPassValidate: true,
  1137. expectedPodSC: podSC(utilpointer.Int64Ptr(1)),
  1138. expectedContainerSC: nil,
  1139. expectedPSP: runAsAny.Name,
  1140. },
  1141. "runAsAny container request": {
  1142. pod: createPodWithSecurityContexts(nil, containerSC(utilpointer.Int64Ptr(1))),
  1143. psps: []*policy.PodSecurityPolicy{runAsAny},
  1144. shouldPassAdmit: true,
  1145. shouldPassValidate: true,
  1146. expectedPodSC: nil,
  1147. expectedContainerSC: containerSC(utilpointer.Int64Ptr(1)),
  1148. expectedPSP: runAsAny.Name,
  1149. },
  1150. "mustRunAs pod request out of range": {
  1151. pod: createPodWithSecurityContexts(podSC(utilpointer.Int64Ptr(1)), nil),
  1152. psps: []*policy.PodSecurityPolicy{mustRunAs},
  1153. shouldPassAdmit: false,
  1154. shouldPassValidate: false,
  1155. },
  1156. "mustRunAs container request out of range": {
  1157. pod: createPodWithSecurityContexts(podSC(utilpointer.Int64Ptr(999)), containerSC(utilpointer.Int64Ptr(1))),
  1158. psps: []*policy.PodSecurityPolicy{mustRunAs},
  1159. shouldPassAdmit: false,
  1160. shouldPassValidate: false,
  1161. },
  1162. "mustRunAs pod request in range": {
  1163. pod: createPodWithSecurityContexts(podSC(utilpointer.Int64Ptr(999)), nil),
  1164. psps: []*policy.PodSecurityPolicy{mustRunAs},
  1165. shouldPassAdmit: true,
  1166. shouldPassValidate: true,
  1167. expectedPodSC: podSC(&mustRunAs.Spec.RunAsUser.Ranges[0].Min),
  1168. expectedContainerSC: nil,
  1169. expectedPSP: mustRunAs.Name,
  1170. },
  1171. "mustRunAs container request in range": {
  1172. pod: createPodWithSecurityContexts(nil, containerSC(utilpointer.Int64Ptr(999))),
  1173. psps: []*policy.PodSecurityPolicy{mustRunAs},
  1174. shouldPassAdmit: true,
  1175. shouldPassValidate: true,
  1176. expectedPodSC: nil,
  1177. expectedContainerSC: containerSC(&mustRunAs.Spec.RunAsUser.Ranges[0].Min),
  1178. expectedPSP: mustRunAs.Name,
  1179. },
  1180. "mustRunAs pod and container request in range": {
  1181. pod: createPodWithSecurityContexts(podSC(utilpointer.Int64Ptr(999)), containerSC(utilpointer.Int64Ptr(1000))),
  1182. psps: []*policy.PodSecurityPolicy{mustRunAs},
  1183. shouldPassAdmit: true,
  1184. shouldPassValidate: true,
  1185. expectedPodSC: podSC(utilpointer.Int64Ptr(999)),
  1186. expectedContainerSC: containerSC(utilpointer.Int64Ptr(1000)),
  1187. expectedPSP: mustRunAs.Name,
  1188. },
  1189. "mustRunAs no request": {
  1190. pod: createPodWithSecurityContexts(nil, nil),
  1191. psps: []*policy.PodSecurityPolicy{mustRunAs},
  1192. shouldPassAdmit: true,
  1193. shouldPassValidate: true,
  1194. expectedPodSC: nil,
  1195. expectedContainerSC: containerSC(&mustRunAs.Spec.RunAsUser.Ranges[0].Min),
  1196. expectedPSP: mustRunAs.Name,
  1197. },
  1198. "runAsNonRoot no request": {
  1199. pod: createPodWithSecurityContexts(nil, nil),
  1200. psps: []*policy.PodSecurityPolicy{runAsNonRoot},
  1201. shouldPassAdmit: true,
  1202. shouldPassValidate: true,
  1203. expectedPodSC: nil,
  1204. expectedContainerSC: &kapi.SecurityContext{RunAsNonRoot: &trueValue},
  1205. expectedPSP: runAsNonRoot.Name,
  1206. },
  1207. "runAsNonRoot pod request root": {
  1208. pod: createPodWithSecurityContexts(podSC(utilpointer.Int64Ptr(0)), nil),
  1209. psps: []*policy.PodSecurityPolicy{runAsNonRoot},
  1210. shouldPassAdmit: false,
  1211. shouldPassValidate: false,
  1212. },
  1213. "runAsNonRoot pod request non-root": {
  1214. pod: createPodWithSecurityContexts(podSC(utilpointer.Int64Ptr(1)), nil),
  1215. psps: []*policy.PodSecurityPolicy{runAsNonRoot},
  1216. shouldPassAdmit: true,
  1217. shouldPassValidate: true,
  1218. expectedPodSC: podSC(utilpointer.Int64Ptr(1)),
  1219. expectedPSP: runAsNonRoot.Name,
  1220. },
  1221. "runAsNonRoot container request root": {
  1222. pod: createPodWithSecurityContexts(podSC(utilpointer.Int64Ptr(1)), containerSC(utilpointer.Int64Ptr(0))),
  1223. psps: []*policy.PodSecurityPolicy{runAsNonRoot},
  1224. shouldPassAdmit: false,
  1225. shouldPassValidate: false,
  1226. },
  1227. "runAsNonRoot container request non-root": {
  1228. pod: createPodWithSecurityContexts(podSC(utilpointer.Int64Ptr(1)), containerSC(utilpointer.Int64Ptr(2))),
  1229. psps: []*policy.PodSecurityPolicy{runAsNonRoot},
  1230. shouldPassAdmit: true,
  1231. shouldPassValidate: true,
  1232. expectedPodSC: podSC(utilpointer.Int64Ptr(1)),
  1233. expectedContainerSC: containerSC(utilpointer.Int64Ptr(2)),
  1234. expectedPSP: runAsNonRoot.Name,
  1235. },
  1236. }
  1237. for k, v := range tests {
  1238. testPSPAdmit(k, v.psps, v.pod, v.shouldPassAdmit, v.shouldPassValidate, v.expectedPSP, t)
  1239. if v.shouldPassAdmit {
  1240. if !reflect.DeepEqual(v.expectedPodSC, v.pod.Spec.SecurityContext) {
  1241. t.Errorf("%s unexpected pod sc diff:\n%s", k, diff.ObjectGoPrintSideBySide(v.expectedPodSC, v.pod.Spec.SecurityContext))
  1242. }
  1243. if !reflect.DeepEqual(v.expectedContainerSC, v.pod.Spec.Containers[0].SecurityContext) {
  1244. t.Errorf("%s unexpected container sc diff:\n%s", k, diff.ObjectGoPrintSideBySide(v.expectedContainerSC, v.pod.Spec.Containers[0].SecurityContext))
  1245. }
  1246. }
  1247. }
  1248. }
  1249. func TestAdmitSupplementalGroups(t *testing.T) {
  1250. podSC := func(group int64) *kapi.PodSecurityContext {
  1251. return &kapi.PodSecurityContext{SupplementalGroups: []int64{group}}
  1252. }
  1253. runAsAny := permissivePSP()
  1254. runAsAny.Name = "runAsAny"
  1255. runAsAny.Spec.SupplementalGroups.Rule = policy.SupplementalGroupsStrategyRunAsAny
  1256. mustRunAs := permissivePSP()
  1257. mustRunAs.Name = "mustRunAs"
  1258. mustRunAs.Spec.SupplementalGroups.Rule = policy.SupplementalGroupsStrategyMustRunAs
  1259. mustRunAs.Spec.SupplementalGroups.Ranges = []policy.IDRange{{Min: int64(999), Max: int64(1000)}}
  1260. tests := map[string]struct {
  1261. pod *kapi.Pod
  1262. psps []*policy.PodSecurityPolicy
  1263. shouldPassAdmit bool
  1264. shouldPassValidate bool
  1265. expectedPodSC *kapi.PodSecurityContext
  1266. expectedPSP string
  1267. }{
  1268. "runAsAny no pod request": {
  1269. pod: createPodWithSecurityContexts(nil, nil),
  1270. psps: []*policy.PodSecurityPolicy{runAsAny},
  1271. shouldPassAdmit: true,
  1272. shouldPassValidate: true,
  1273. expectedPodSC: nil,
  1274. expectedPSP: runAsAny.Name,
  1275. },
  1276. "runAsAny empty pod request": {
  1277. pod: createPodWithSecurityContexts(&kapi.PodSecurityContext{}, nil),
  1278. psps: []*policy.PodSecurityPolicy{runAsAny},
  1279. shouldPassAdmit: true,
  1280. shouldPassValidate: true,
  1281. expectedPodSC: &kapi.PodSecurityContext{},
  1282. expectedPSP: runAsAny.Name,
  1283. },
  1284. "runAsAny empty pod request empty supplemental groups": {
  1285. pod: createPodWithSecurityContexts(&kapi.PodSecurityContext{SupplementalGroups: []int64{}}, nil),
  1286. psps: []*policy.PodSecurityPolicy{runAsAny},
  1287. shouldPassAdmit: true,
  1288. shouldPassValidate: true,
  1289. expectedPodSC: &kapi.PodSecurityContext{SupplementalGroups: []int64{}},
  1290. expectedPSP: runAsAny.Name,
  1291. },
  1292. "runAsAny pod request": {
  1293. pod: createPodWithSecurityContexts(podSC(1), nil),
  1294. psps: []*policy.PodSecurityPolicy{runAsAny},
  1295. shouldPassAdmit: true,
  1296. shouldPassValidate: true,
  1297. expectedPodSC: &kapi.PodSecurityContext{SupplementalGroups: []int64{1}},
  1298. expectedPSP: runAsAny.Name,
  1299. },
  1300. "mustRunAs no pod request": {
  1301. pod: createPodWithSecurityContexts(nil, nil),
  1302. psps: []*policy.PodSecurityPolicy{mustRunAs},
  1303. shouldPassAdmit: true,
  1304. shouldPassValidate: true,
  1305. expectedPodSC: podSC(mustRunAs.Spec.SupplementalGroups.Ranges[0].Min),
  1306. expectedPSP: mustRunAs.Name,
  1307. },
  1308. "mustRunAs bad pod request": {
  1309. pod: createPodWithSecurityContexts(podSC(1), nil),
  1310. psps: []*policy.PodSecurityPolicy{mustRunAs},
  1311. shouldPassAdmit: false,
  1312. shouldPassValidate: false,
  1313. },
  1314. "mustRunAs good pod request": {
  1315. pod: createPodWithSecurityContexts(podSC(999), nil),
  1316. psps: []*policy.PodSecurityPolicy{mustRunAs},
  1317. shouldPassAdmit: true,
  1318. shouldPassValidate: true,
  1319. expectedPodSC: podSC(999),
  1320. expectedPSP: mustRunAs.Name,
  1321. },
  1322. }
  1323. for k, v := range tests {
  1324. testPSPAdmit(k, v.psps, v.pod, v.shouldPassAdmit, v.shouldPassValidate, v.expectedPSP, t)
  1325. if v.shouldPassAdmit {
  1326. if !reflect.DeepEqual(v.expectedPodSC, v.pod.Spec.SecurityContext) {
  1327. t.Errorf("%s unexpected pod sc diff:\n%s", k, diff.ObjectGoPrintSideBySide(v.expectedPodSC, v.pod.Spec.SecurityContext))
  1328. }
  1329. }
  1330. }
  1331. }
  1332. func TestAdmitFSGroup(t *testing.T) {
  1333. createPodWithFSGroup := func(group int64) *kapi.Pod {
  1334. pod := goodPod()
  1335. // doesn't matter if we set it here or on the container, the
  1336. // admission controller uses DetermineEffectiveSC to get the defaulting
  1337. // behavior so it can validate what will be applied at runtime
  1338. pod.Spec.SecurityContext.FSGroup = utilpointer.Int64Ptr(group)
  1339. return pod
  1340. }
  1341. runAsAny := restrictivePSP()
  1342. runAsAny.Name = "runAsAny"
  1343. runAsAny.Spec.FSGroup.Rule = policy.FSGroupStrategyRunAsAny
  1344. mustRunAs := restrictivePSP()
  1345. mustRunAs.Name = "mustRunAs"
  1346. tests := map[string]struct {
  1347. pod *kapi.Pod
  1348. psps []*policy.PodSecurityPolicy
  1349. shouldPassAdmit bool
  1350. shouldPassValidate bool
  1351. expectedFSGroup *int64
  1352. expectedPSP string
  1353. }{
  1354. "runAsAny no pod request": {
  1355. pod: goodPod(),
  1356. psps: []*policy.PodSecurityPolicy{runAsAny},
  1357. shouldPassAdmit: true,
  1358. shouldPassValidate: true,
  1359. expectedFSGroup: nil,
  1360. expectedPSP: runAsAny.Name,
  1361. },
  1362. "runAsAny pod request": {
  1363. pod: createPodWithFSGroup(1),
  1364. psps: []*policy.PodSecurityPolicy{runAsAny},
  1365. shouldPassAdmit: true,
  1366. shouldPassValidate: true,
  1367. expectedFSGroup: utilpointer.Int64Ptr(1),
  1368. expectedPSP: runAsAny.Name,
  1369. },
  1370. "mustRunAs no pod request": {
  1371. pod: goodPod(),
  1372. psps: []*policy.PodSecurityPolicy{mustRunAs},
  1373. shouldPassAdmit: true,
  1374. shouldPassValidate: true,
  1375. expectedFSGroup: &mustRunAs.Spec.SupplementalGroups.Ranges[0].Min,
  1376. expectedPSP: mustRunAs.Name,
  1377. },
  1378. "mustRunAs bad pod request": {
  1379. pod: createPodWithFSGroup(1),
  1380. psps: []*policy.PodSecurityPolicy{mustRunAs},
  1381. shouldPassAdmit: false,
  1382. shouldPassValidate: false,
  1383. },
  1384. "mustRunAs good pod request": {
  1385. pod: createPodWithFSGroup(999),
  1386. psps: []*policy.PodSecurityPolicy{mustRunAs},
  1387. shouldPassAdmit: true,
  1388. shouldPassValidate: true,
  1389. expectedFSGroup: utilpointer.Int64Ptr(999),
  1390. expectedPSP: mustRunAs.Name,
  1391. },
  1392. }
  1393. for k, v := range tests {
  1394. testPSPAdmit(k, v.psps, v.pod, v.shouldPassAdmit, v.shouldPassValidate, v.expectedPSP, t)
  1395. if v.shouldPassAdmit {
  1396. if v.pod.Spec.SecurityContext.FSGroup == nil && v.expectedFSGroup == nil {
  1397. // ok, don't need to worry about identifying specific diffs
  1398. continue
  1399. }
  1400. if v.pod.Spec.SecurityContext.FSGroup == nil && v.expectedFSGroup != nil {
  1401. t.Errorf("%s expected FSGroup to be: %v but found nil", k, *v.expectedFSGroup)
  1402. continue
  1403. }
  1404. if v.pod.Spec.SecurityContext.FSGroup != nil && v.expectedFSGroup == nil {
  1405. t.Errorf("%s expected FSGroup to be nil but found: %v", k, *v.pod.Spec.SecurityContext.FSGroup)
  1406. continue
  1407. }
  1408. if *v.expectedFSGroup != *v.pod.Spec.SecurityContext.FSGroup {
  1409. t.Errorf("%s expected FSGroup to be: %v but found %v", k, *v.expectedFSGroup, *v.pod.Spec.SecurityContext.FSGroup)
  1410. }
  1411. }
  1412. }
  1413. }
  1414. func TestAdmitReadOnlyRootFilesystem(t *testing.T) {
  1415. createPodWithRORFS := func(rorfs bool) *kapi.Pod {
  1416. pod := goodPod()
  1417. pod.Spec.Containers[0].SecurityContext.ReadOnlyRootFilesystem = &rorfs
  1418. return pod
  1419. }
  1420. noRORFS := restrictivePSP()
  1421. noRORFS.Name = "no-rorfs"
  1422. noRORFS.Spec.ReadOnlyRootFilesystem = false
  1423. rorfs := restrictivePSP()
  1424. rorfs.Name = "rorfs"
  1425. rorfs.Spec.ReadOnlyRootFilesystem = true
  1426. tests := map[string]struct {
  1427. pod *kapi.Pod
  1428. psps []*policy.PodSecurityPolicy
  1429. shouldPassAdmit bool
  1430. shouldPassValidate bool
  1431. expectedRORFS bool
  1432. expectedPSP string
  1433. }{
  1434. "no-rorfs allows pod request with rorfs": {
  1435. pod: createPodWithRORFS(true),
  1436. psps: []*policy.PodSecurityPolicy{noRORFS},
  1437. shouldPassAdmit: true,
  1438. shouldPassValidate: true,
  1439. expectedRORFS: true,
  1440. expectedPSP: noRORFS.Name,
  1441. },
  1442. "no-rorfs allows pod request without rorfs": {
  1443. pod: createPodWithRORFS(false),
  1444. psps: []*policy.PodSecurityPolicy{noRORFS},
  1445. shouldPassAdmit: true,
  1446. shouldPassValidate: true,
  1447. expectedRORFS: false,
  1448. expectedPSP: noRORFS.Name,
  1449. },
  1450. "rorfs rejects pod request without rorfs": {
  1451. pod: createPodWithRORFS(false),
  1452. psps: []*policy.PodSecurityPolicy{rorfs},
  1453. shouldPassAdmit: false,
  1454. shouldPassValidate: false,
  1455. },
  1456. "rorfs defaults nil pod request": {
  1457. pod: goodPod(),
  1458. psps: []*policy.PodSecurityPolicy{rorfs},
  1459. shouldPassAdmit: true,
  1460. shouldPassValidate: true,
  1461. expectedRORFS: true,
  1462. expectedPSP: rorfs.Name,
  1463. },
  1464. "rorfs accepts pod request with rorfs": {
  1465. pod: createPodWithRORFS(true),
  1466. psps: []*policy.PodSecurityPolicy{rorfs},
  1467. shouldPassAdmit: true,
  1468. shouldPassValidate: true,
  1469. expectedRORFS: true,
  1470. expectedPSP: rorfs.Name,
  1471. },
  1472. }
  1473. for k, v := range tests {
  1474. testPSPAdmit(k, v.psps, v.pod, v.shouldPassAdmit, v.shouldPassValidate, v.expectedPSP, t)
  1475. if v.shouldPassAdmit {
  1476. if v.pod.Spec.Containers[0].SecurityContext.ReadOnlyRootFilesystem == nil ||
  1477. *v.pod.Spec.Containers[0].SecurityContext.ReadOnlyRootFilesystem != v.expectedRORFS {
  1478. t.Errorf("%s expected ReadOnlyRootFilesystem to be %t but found %#v", k, v.expectedRORFS, v.pod.Spec.Containers[0].SecurityContext.ReadOnlyRootFilesystem)
  1479. }
  1480. }
  1481. }
  1482. }
  1483. func TestAdmitSysctls(t *testing.T) {
  1484. podWithSysctls := func(safeSysctls []string, unsafeSysctls []string) *kapi.Pod {
  1485. pod := goodPod()
  1486. dummySysctls := func(names []string) []kapi.Sysctl {
  1487. sysctls := make([]kapi.Sysctl, len(names))
  1488. for i, n := range names {
  1489. sysctls[i].Name = n
  1490. sysctls[i].Value = "dummy"
  1491. }
  1492. return sysctls
  1493. }
  1494. pod.Spec.SecurityContext = &kapi.PodSecurityContext{
  1495. Sysctls: dummySysctls(append(safeSysctls, unsafeSysctls...)),
  1496. }
  1497. return pod
  1498. }
  1499. safeSysctls := restrictivePSP()
  1500. safeSysctls.Name = "no sysctls"
  1501. noSysctls := restrictivePSP()
  1502. noSysctls.Name = "empty sysctls"
  1503. noSysctls.Spec.ForbiddenSysctls = []string{"*"}
  1504. mixedSysctls := restrictivePSP()
  1505. mixedSysctls.Name = "wildcard sysctls"
  1506. mixedSysctls.Spec.ForbiddenSysctls = []string{"net.*"}
  1507. mixedSysctls.Spec.AllowedUnsafeSysctls = []string{"a.*", "b.*"}
  1508. aUnsafeSysctl := restrictivePSP()
  1509. aUnsafeSysctl.Name = "a sysctl"
  1510. aUnsafeSysctl.Spec.AllowedUnsafeSysctls = []string{"a"}
  1511. bUnsafeSysctl := restrictivePSP()
  1512. bUnsafeSysctl.Name = "b sysctl"
  1513. bUnsafeSysctl.Spec.AllowedUnsafeSysctls = []string{"b"}
  1514. cUnsafeSysctl := restrictivePSP()
  1515. cUnsafeSysctl.Name = "c sysctl"
  1516. cUnsafeSysctl.Spec.AllowedUnsafeSysctls = []string{"c"}
  1517. catchallSysctls := restrictivePSP()
  1518. catchallSysctls.Name = "catchall sysctl"
  1519. catchallSysctls.Spec.AllowedUnsafeSysctls = []string{"*"}
  1520. tests := map[string]struct {
  1521. pod *kapi.Pod
  1522. psps []*policy.PodSecurityPolicy
  1523. shouldPassAdmit bool
  1524. shouldPassValidate bool
  1525. expectedPSP string
  1526. }{
  1527. "pod without any sysctls request allowed under safeSysctls PSP": {
  1528. pod: goodPod(),
  1529. psps: []*policy.PodSecurityPolicy{safeSysctls},
  1530. shouldPassAdmit: true,
  1531. shouldPassValidate: true,
  1532. expectedPSP: safeSysctls.Name,
  1533. },
  1534. "pod without any sysctls request allowed under noSysctls PSP": {
  1535. pod: goodPod(),
  1536. psps: []*policy.PodSecurityPolicy{noSysctls},
  1537. shouldPassAdmit: true,
  1538. shouldPassValidate: true,
  1539. expectedPSP: noSysctls.Name,
  1540. },
  1541. "pod with safe sysctls request allowed under safeSysctls PSP": {
  1542. pod: podWithSysctls([]string{"kernel.shm_rmid_forced", "net.ipv4.tcp_syncookies"}, []string{}),
  1543. psps: []*policy.PodSecurityPolicy{safeSysctls},
  1544. shouldPassAdmit: true,
  1545. shouldPassValidate: true,
  1546. expectedPSP: safeSysctls.Name,
  1547. },
  1548. "pod with unsafe sysctls request disallowed under noSysctls PSP": {
  1549. pod: podWithSysctls([]string{}, []string{"a", "b"}),
  1550. psps: []*policy.PodSecurityPolicy{noSysctls},
  1551. shouldPassAdmit: false,
  1552. shouldPassValidate: false,
  1553. expectedPSP: noSysctls.Name,
  1554. },
  1555. "pod with unsafe sysctls a, b request disallowed under aUnsafeSysctl SCC": {
  1556. pod: podWithSysctls([]string{}, []string{"a", "b"}),
  1557. psps: []*policy.PodSecurityPolicy{aUnsafeSysctl},
  1558. shouldPassAdmit: false,
  1559. shouldPassValidate: false,
  1560. },
  1561. "pod with unsafe sysctls b request disallowed under aUnsafeSysctl SCC": {
  1562. pod: podWithSysctls([]string{}, []string{"b"}),
  1563. psps: []*policy.PodSecurityPolicy{aUnsafeSysctl},
  1564. shouldPassAdmit: false,
  1565. shouldPassValidate: false,
  1566. },
  1567. "pod with unsafe sysctls a request allowed under aUnsafeSysctl SCC": {
  1568. pod: podWithSysctls([]string{}, []string{"a"}),
  1569. psps: []*policy.PodSecurityPolicy{aUnsafeSysctl},
  1570. shouldPassAdmit: true,
  1571. shouldPassValidate: true,
  1572. expectedPSP: aUnsafeSysctl.Name,
  1573. },
  1574. "pod with safe net sysctl request allowed under aUnsafeSysctl SCC": {
  1575. pod: podWithSysctls([]string{"net.ipv4.ip_local_port_range"}, []string{}),
  1576. psps: []*policy.PodSecurityPolicy{aUnsafeSysctl},
  1577. shouldPassAdmit: true,
  1578. shouldPassValidate: true,
  1579. expectedPSP: aUnsafeSysctl.Name,
  1580. },
  1581. "pod with safe sysctls request disallowed under noSysctls PSP": {
  1582. pod: podWithSysctls([]string{"net.ipv4.ip_local_port_range"}, []string{}),
  1583. psps: []*policy.PodSecurityPolicy{noSysctls},
  1584. shouldPassAdmit: false,
  1585. shouldPassValidate: false,
  1586. },
  1587. "pod with matching sysctls request allowed under mixedSysctls PSP": {
  1588. pod: podWithSysctls([]string{"kernel.shm_rmid_forced"}, []string{"a.b", "b.a"}),
  1589. psps: []*policy.PodSecurityPolicy{mixedSysctls},
  1590. shouldPassAdmit: true,
  1591. shouldPassValidate: true,
  1592. expectedPSP: mixedSysctls.Name,
  1593. },
  1594. "pod with not-matching unsafe sysctls request disallowed under mixedSysctls PSP": {
  1595. pod: podWithSysctls([]string{}, []string{"e"}),
  1596. psps: []*policy.PodSecurityPolicy{mixedSysctls},
  1597. shouldPassAdmit: false,
  1598. shouldPassValidate: false,
  1599. },
  1600. "pod with not-matching safe sysctls request disallowed under mixedSysctls PSP": {
  1601. pod: podWithSysctls([]string{"net.ipv4.ip_local_port_range"}, []string{}),
  1602. psps: []*policy.PodSecurityPolicy{mixedSysctls},
  1603. shouldPassAdmit: false,
  1604. shouldPassValidate: false,
  1605. },
  1606. "pod with sysctls request allowed under catchallSysctls PSP": {
  1607. pod: podWithSysctls([]string{"net.ipv4.ip_local_port_range"}, []string{"f"}),
  1608. psps: []*policy.PodSecurityPolicy{catchallSysctls},
  1609. shouldPassAdmit: true,
  1610. shouldPassValidate: true,
  1611. expectedPSP: catchallSysctls.Name,
  1612. },
  1613. }
  1614. for k, v := range tests {
  1615. origSysctl := v.pod.Spec.SecurityContext.Sysctls
  1616. testPSPAdmit(k, v.psps, v.pod, v.shouldPassAdmit, v.shouldPassValidate, v.expectedPSP, t)
  1617. if v.shouldPassAdmit {
  1618. if !reflect.DeepEqual(v.pod.Spec.SecurityContext.Sysctls, origSysctl) {
  1619. t.Errorf("%s: wrong sysctls: expected=%v, got=%v", k, origSysctl, v.pod.Spec.SecurityContext.Sysctls)
  1620. }
  1621. }
  1622. }
  1623. }
  1624. func testPSPAdmit(testCaseName string, psps []*policy.PodSecurityPolicy, pod *kapi.Pod, shouldPassAdmit, shouldPassValidate bool, expectedPSP string, t *testing.T) {
  1625. testPSPAdmitAdvanced(testCaseName, kadmission.Create, psps, nil, &user.DefaultInfo{}, pod, nil, shouldPassAdmit, shouldPassValidate, true, expectedPSP, t)
  1626. }
  1627. // fakeAttributes decorate kadmission.Attributes. It's used to trace the added annotations.
  1628. type fakeAttributes struct {
  1629. kadmission.Attributes
  1630. annotations map[string]string
  1631. }
  1632. func (f fakeAttributes) AddAnnotation(k, v string) error {
  1633. f.annotations[k] = v
  1634. return f.Attributes.AddAnnotation(k, v)
  1635. }
  1636. func testPSPAdmitAdvanced(testCaseName string, op kadmission.Operation, psps []*policy.PodSecurityPolicy, authz authorizer.Authorizer, userInfo user.Info, pod, oldPod *kapi.Pod, shouldPassAdmit, shouldPassValidate bool, canMutate bool, expectedPSP string, t *testing.T) {
  1637. originalPod := pod.DeepCopy()
  1638. plugin := NewTestAdmission(psps, authz)
  1639. attrs := kadmission.NewAttributesRecord(pod, oldPod, kapi.Kind("Pod").WithVersion("version"), pod.Namespace, "", kapi.Resource("pods").WithVersion("version"), "", op, nil, false, userInfo)
  1640. annotations := make(map[string]string)
  1641. attrs = &fakeAttributes{attrs, annotations}
  1642. err := admissiontesting.WithReinvocationTesting(t, plugin).Admit(attrs, nil)
  1643. if shouldPassAdmit && err != nil {
  1644. t.Errorf("%s: expected no errors on Admit but received %v", testCaseName, err)
  1645. }
  1646. if shouldPassAdmit && err == nil {
  1647. if pod.Annotations[psputil.ValidatedPSPAnnotation] != expectedPSP {
  1648. t.Errorf("%s: expected to be admitted under %q PSP but found %q", testCaseName, expectedPSP, pod.Annotations[psputil.ValidatedPSPAnnotation])
  1649. }
  1650. if !canMutate {
  1651. podWithoutPSPAnnotation := pod.DeepCopy()
  1652. delete(podWithoutPSPAnnotation.Annotations, psputil.ValidatedPSPAnnotation)
  1653. originalPodWithoutPSPAnnotation := originalPod.DeepCopy()
  1654. delete(originalPodWithoutPSPAnnotation.Annotations, psputil.ValidatedPSPAnnotation)
  1655. if !apiequality.Semantic.DeepEqual(originalPodWithoutPSPAnnotation.Spec, podWithoutPSPAnnotation.Spec) {
  1656. t.Errorf("%s: expected no mutation on Admit, got %s", testCaseName, diff.ObjectGoPrintSideBySide(originalPodWithoutPSPAnnotation.Spec, podWithoutPSPAnnotation.Spec))
  1657. }
  1658. }
  1659. }
  1660. if !shouldPassAdmit && err == nil {
  1661. t.Errorf("%s: expected errors on Admit but received none", testCaseName)
  1662. }
  1663. err = plugin.Validate(attrs, nil)
  1664. psp := ""
  1665. if shouldPassAdmit && op == kadmission.Create {
  1666. psp = expectedPSP
  1667. }
  1668. validateAuditAnnotation(t, testCaseName, annotations, "podsecuritypolicy.policy.k8s.io/admit-policy", psp)
  1669. if shouldPassValidate && err != nil {
  1670. t.Errorf("%s: expected no errors on Validate but received %v", testCaseName, err)
  1671. } else if !shouldPassValidate && err == nil {
  1672. t.Errorf("%s: expected errors on Validate but received none", testCaseName)
  1673. }
  1674. if shouldPassValidate {
  1675. validateAuditAnnotation(t, testCaseName, annotations, "podsecuritypolicy.policy.k8s.io/validate-policy", expectedPSP)
  1676. } else {
  1677. validateAuditAnnotation(t, testCaseName, annotations, "podsecuritypolicy.policy.k8s.io/validate-policy", "")
  1678. }
  1679. }
  1680. func validateAuditAnnotation(t *testing.T, testCaseName string, annotations map[string]string, key, value string) {
  1681. if annotations[key] != value {
  1682. t.Errorf("%s: expected to have annotations[%s] set to %q, got %q", testCaseName, key, value, annotations[key])
  1683. }
  1684. }
  1685. func TestAssignSecurityContext(t *testing.T) {
  1686. // psp that will deny privileged container requests and has a default value for a field (uid)
  1687. psp := restrictivePSP()
  1688. provider, err := kpsp.NewSimpleProvider(psp, "namespace", kpsp.NewSimpleStrategyFactory())
  1689. if err != nil {
  1690. t.Fatalf("failed to create provider: %v", err)
  1691. }
  1692. createContainer := func(priv bool) kapi.Container {
  1693. return kapi.Container{
  1694. SecurityContext: &kapi.SecurityContext{
  1695. Privileged: &priv,
  1696. },
  1697. }
  1698. }
  1699. testCases := map[string]struct {
  1700. pod *kapi.Pod
  1701. shouldValidate bool
  1702. expectedUID *int64
  1703. }{
  1704. "pod and container SC is not changed when invalid": {
  1705. pod: &kapi.Pod{
  1706. Spec: kapi.PodSpec{
  1707. SecurityContext: &kapi.PodSecurityContext{},
  1708. Containers: []kapi.Container{createContainer(true)},
  1709. },
  1710. },
  1711. shouldValidate: false,
  1712. },
  1713. "must validate all containers": {
  1714. pod: &kapi.Pod{
  1715. Spec: kapi.PodSpec{
  1716. // good container and bad container
  1717. SecurityContext: &kapi.PodSecurityContext{},
  1718. Containers: []kapi.Container{createContainer(false), createContainer(true)},
  1719. },
  1720. },
  1721. shouldValidate: false,
  1722. },
  1723. "pod validates": {
  1724. pod: &kapi.Pod{
  1725. Spec: kapi.PodSpec{
  1726. SecurityContext: &kapi.PodSecurityContext{},
  1727. Containers: []kapi.Container{createContainer(false)},
  1728. },
  1729. },
  1730. shouldValidate: true,
  1731. },
  1732. }
  1733. for k, v := range testCases {
  1734. errs := assignSecurityContext(provider, v.pod)
  1735. if v.shouldValidate && len(errs) > 0 {
  1736. t.Errorf("%s expected to validate but received errors %v", k, errs)
  1737. continue
  1738. }
  1739. if !v.shouldValidate && len(errs) == 0 {
  1740. t.Errorf("%s expected validation errors but received none", k)
  1741. continue
  1742. }
  1743. }
  1744. }
  1745. func TestCreateProvidersFromConstraints(t *testing.T) {
  1746. testCases := map[string]struct {
  1747. // use a generating function so we can test for non-mutation
  1748. psp func() *policy.PodSecurityPolicy
  1749. expectedErr string
  1750. }{
  1751. "valid psp": {
  1752. psp: func() *policy.PodSecurityPolicy {
  1753. return &policy.PodSecurityPolicy{
  1754. ObjectMeta: metav1.ObjectMeta{
  1755. Name: "valid psp",
  1756. },
  1757. Spec: policy.PodSecurityPolicySpec{
  1758. SELinux: policy.SELinuxStrategyOptions{
  1759. Rule: policy.SELinuxStrategyRunAsAny,
  1760. },
  1761. RunAsUser: policy.RunAsUserStrategyOptions{
  1762. Rule: policy.RunAsUserStrategyRunAsAny,
  1763. },
  1764. RunAsGroup: &policy.RunAsGroupStrategyOptions{
  1765. Rule: policy.RunAsGroupStrategyRunAsAny,
  1766. },
  1767. FSGroup: policy.FSGroupStrategyOptions{
  1768. Rule: policy.FSGroupStrategyRunAsAny,
  1769. },
  1770. SupplementalGroups: policy.SupplementalGroupsStrategyOptions{
  1771. Rule: policy.SupplementalGroupsStrategyRunAsAny,
  1772. },
  1773. },
  1774. }
  1775. },
  1776. },
  1777. "bad psp strategy options": {
  1778. psp: func() *policy.PodSecurityPolicy {
  1779. return &policy.PodSecurityPolicy{
  1780. ObjectMeta: metav1.ObjectMeta{
  1781. Name: "bad psp user options",
  1782. },
  1783. Spec: policy.PodSecurityPolicySpec{
  1784. SELinux: policy.SELinuxStrategyOptions{
  1785. Rule: policy.SELinuxStrategyRunAsAny,
  1786. },
  1787. RunAsUser: policy.RunAsUserStrategyOptions{
  1788. Rule: policy.RunAsUserStrategyMustRunAs,
  1789. },
  1790. RunAsGroup: &policy.RunAsGroupStrategyOptions{
  1791. Rule: policy.RunAsGroupStrategyRunAsAny,
  1792. },
  1793. FSGroup: policy.FSGroupStrategyOptions{
  1794. Rule: policy.FSGroupStrategyRunAsAny,
  1795. },
  1796. SupplementalGroups: policy.SupplementalGroupsStrategyOptions{
  1797. Rule: policy.SupplementalGroupsStrategyRunAsAny,
  1798. },
  1799. },
  1800. }
  1801. },
  1802. expectedErr: "MustRunAs requires at least one range",
  1803. },
  1804. }
  1805. for k, v := range testCases {
  1806. admit := &Plugin{
  1807. Handler: kadmission.NewHandler(kadmission.Create, kadmission.Update),
  1808. strategyFactory: kpsp.NewSimpleStrategyFactory(),
  1809. }
  1810. psp := v.psp()
  1811. _, errs := admit.createProvidersFromPolicies([]*policy.PodSecurityPolicy{psp}, "namespace")
  1812. if !reflect.DeepEqual(psp, v.psp()) {
  1813. diff := diff.ObjectDiff(psp, v.psp())
  1814. t.Errorf("%s createProvidersFromPolicies mutated policy. diff:\n%s", k, diff)
  1815. }
  1816. if len(v.expectedErr) > 0 && len(errs) != 1 {
  1817. t.Errorf("%s expected a single error '%s' but received %v", k, v.expectedErr, errs)
  1818. continue
  1819. }
  1820. if len(v.expectedErr) == 0 && len(errs) != 0 {
  1821. t.Errorf("%s did not expect an error but received %v", k, errs)
  1822. continue
  1823. }
  1824. // check that we got the error we expected
  1825. if len(v.expectedErr) > 0 {
  1826. if !strings.Contains(errs[0].Error(), v.expectedErr) {
  1827. t.Errorf("%s expected error '%s' but received %v", k, v.expectedErr, errs[0])
  1828. }
  1829. }
  1830. }
  1831. }
  1832. func TestPolicyAuthorization(t *testing.T) {
  1833. policyWithName := func(name string) *policy.PodSecurityPolicy {
  1834. p := permissivePSP()
  1835. p.Name = name
  1836. return p
  1837. }
  1838. tests := map[string]struct {
  1839. user user.Info
  1840. sa string
  1841. ns string
  1842. expectedPolicy string
  1843. inPolicies []*policy.PodSecurityPolicy
  1844. allowed map[string]map[string]map[string]bool
  1845. allowedGroup string
  1846. }{
  1847. "policy allowed by user (extensions API Group)": {
  1848. user: &user.DefaultInfo{Name: "user"},
  1849. sa: "sa",
  1850. ns: "test",
  1851. allowed: map[string]map[string]map[string]bool{
  1852. "user": {
  1853. "test": {"policy": true},
  1854. },
  1855. },
  1856. inPolicies: []*policy.PodSecurityPolicy{policyWithName("policy")},
  1857. expectedPolicy: "policy",
  1858. },
  1859. "policy allowed by sa (extensions API Group)": {
  1860. user: &user.DefaultInfo{Name: "user"},
  1861. sa: "sa",
  1862. ns: "test",
  1863. allowed: map[string]map[string]map[string]bool{
  1864. serviceaccount.MakeUsername("test", "sa"): {
  1865. "test": {"policy": true},
  1866. },
  1867. },
  1868. inPolicies: []*policy.PodSecurityPolicy{policyWithName("policy")},
  1869. expectedPolicy: "policy",
  1870. },
  1871. "policy allowed by user (policy API Group)": {
  1872. user: &user.DefaultInfo{Name: "user"},
  1873. sa: "sa",
  1874. ns: "test",
  1875. allowed: map[string]map[string]map[string]bool{
  1876. "user": {
  1877. "test": {"policy": true},
  1878. },
  1879. },
  1880. inPolicies: []*policy.PodSecurityPolicy{policyWithName("policy")},
  1881. expectedPolicy: "policy",
  1882. allowedGroup: policy.GroupName,
  1883. },
  1884. "policy allowed by sa (policy API Group)": {
  1885. user: &user.DefaultInfo{Name: "user"},
  1886. sa: "sa",
  1887. ns: "test",
  1888. allowed: map[string]map[string]map[string]bool{
  1889. serviceaccount.MakeUsername("test", "sa"): {
  1890. "test": {"policy": true},
  1891. },
  1892. },
  1893. inPolicies: []*policy.PodSecurityPolicy{policyWithName("policy")},
  1894. expectedPolicy: "policy",
  1895. allowedGroup: policy.GroupName,
  1896. },
  1897. "no policies allowed": {
  1898. user: &user.DefaultInfo{Name: "user"},
  1899. sa: "sa",
  1900. ns: "test",
  1901. allowed: map[string]map[string]map[string]bool{},
  1902. inPolicies: []*policy.PodSecurityPolicy{policyWithName("policy")},
  1903. expectedPolicy: "",
  1904. },
  1905. "multiple policies allowed": {
  1906. user: &user.DefaultInfo{Name: "user"},
  1907. sa: "sa",
  1908. ns: "test",
  1909. allowed: map[string]map[string]map[string]bool{
  1910. serviceaccount.MakeUsername("test", "sa"): {
  1911. "test": {"policy1": true},
  1912. "": {"policy4": true},
  1913. "other": {"policy6": true},
  1914. },
  1915. "user": {
  1916. "test": {"policy2": true},
  1917. "": {"policy5": true},
  1918. "other": {"policy7": true},
  1919. },
  1920. },
  1921. inPolicies: []*policy.PodSecurityPolicy{
  1922. // Prefix to force checking these policies first.
  1923. policyWithName("a_policy1"), // not allowed in this namespace
  1924. policyWithName("a_policy2"), // not allowed in this namespace
  1925. policyWithName("policy2"), // allowed by sa
  1926. policyWithName("policy3"), // allowed by user
  1927. policyWithName("policy4"), // not allowed
  1928. policyWithName("policy5"), // allowed by sa at cluster level
  1929. policyWithName("policy6"), // allowed by user at cluster level
  1930. },
  1931. expectedPolicy: "policy2",
  1932. },
  1933. "policies are not allowed for nil user info": {
  1934. user: nil,
  1935. sa: "sa",
  1936. ns: "test",
  1937. allowed: map[string]map[string]map[string]bool{
  1938. serviceaccount.MakeUsername("test", "sa"): {
  1939. "test": {"policy1": true},
  1940. },
  1941. "user": {
  1942. "test": {"policy2": true},
  1943. },
  1944. },
  1945. inPolicies: []*policy.PodSecurityPolicy{
  1946. policyWithName("policy1"),
  1947. policyWithName("policy2"),
  1948. policyWithName("policy3"),
  1949. },
  1950. // only the policies for the sa are allowed when user info is nil
  1951. expectedPolicy: "policy1",
  1952. },
  1953. "policies are not allowed for nil sa info": {
  1954. user: &user.DefaultInfo{Name: "user"},
  1955. sa: "",
  1956. ns: "test",
  1957. allowed: map[string]map[string]map[string]bool{
  1958. serviceaccount.MakeUsername("test", "sa"): {
  1959. "test": {"policy1": true},
  1960. },
  1961. "user": {
  1962. "test": {"policy2": true},
  1963. },
  1964. },
  1965. inPolicies: []*policy.PodSecurityPolicy{
  1966. policyWithName("policy1"),
  1967. policyWithName("policy2"),
  1968. policyWithName("policy3"),
  1969. },
  1970. // only the policies for the user are allowed when sa info is nil
  1971. expectedPolicy: "policy2",
  1972. },
  1973. "policies are not allowed for nil sa and user info": {
  1974. user: nil,
  1975. sa: "",
  1976. ns: "test",
  1977. allowed: map[string]map[string]map[string]bool{
  1978. serviceaccount.MakeUsername("test", "sa"): {
  1979. "test": {"policy1": true},
  1980. },
  1981. "user": {
  1982. "test": {"policy2": true},
  1983. },
  1984. },
  1985. inPolicies: []*policy.PodSecurityPolicy{
  1986. policyWithName("policy1"),
  1987. policyWithName("policy2"),
  1988. policyWithName("policy3"),
  1989. },
  1990. // no policies are allowed if sa and user are both nil
  1991. expectedPolicy: "",
  1992. },
  1993. }
  1994. for k, v := range tests {
  1995. var (
  1996. oldPod *kapi.Pod
  1997. shouldPass = v.expectedPolicy != ""
  1998. authz = &TestAuthorizer{usernameToNamespaceToAllowedPSPs: v.allowed, allowedAPIGroupName: v.allowedGroup}
  1999. canMutate = true
  2000. )
  2001. pod := goodPod()
  2002. pod.Namespace = v.ns
  2003. pod.Spec.ServiceAccountName = v.sa
  2004. testPSPAdmitAdvanced(k, kadmission.Create, v.inPolicies, authz, v.user,
  2005. pod, oldPod, shouldPass, shouldPass, canMutate, v.expectedPolicy, t)
  2006. }
  2007. }
  2008. func TestPolicyAuthorizationErrors(t *testing.T) {
  2009. policyWithName := func(name string) *policy.PodSecurityPolicy {
  2010. p := restrictivePSP()
  2011. p.Name = name
  2012. return p
  2013. }
  2014. const (
  2015. sa = "sa"
  2016. ns = "test"
  2017. userName = "user"
  2018. )
  2019. tests := map[string]struct {
  2020. inPolicies []*policy.PodSecurityPolicy
  2021. allowed map[string]map[string]map[string]bool
  2022. expectValidationErrs int
  2023. }{
  2024. "policies not allowed": {
  2025. allowed: map[string]map[string]map[string]bool{},
  2026. inPolicies: []*policy.PodSecurityPolicy{
  2027. policyWithName("policy1"),
  2028. policyWithName("policy2"),
  2029. },
  2030. expectValidationErrs: 0,
  2031. },
  2032. "policy allowed by user": {
  2033. allowed: map[string]map[string]map[string]bool{
  2034. "user": {
  2035. "test": {"policy1": true},
  2036. },
  2037. },
  2038. inPolicies: []*policy.PodSecurityPolicy{
  2039. policyWithName("policy1"),
  2040. policyWithName("policy2"),
  2041. },
  2042. expectValidationErrs: 1,
  2043. },
  2044. "policy allowed by service account": {
  2045. allowed: map[string]map[string]map[string]bool{
  2046. serviceaccount.MakeUsername("test", "sa"): {
  2047. "test": {"policy2": true},
  2048. },
  2049. },
  2050. inPolicies: []*policy.PodSecurityPolicy{
  2051. policyWithName("policy1"),
  2052. policyWithName("policy2"),
  2053. },
  2054. expectValidationErrs: 1,
  2055. },
  2056. "multiple policies allowed": {
  2057. allowed: map[string]map[string]map[string]bool{
  2058. "user": {
  2059. "test": {"policy1": true},
  2060. },
  2061. serviceaccount.MakeUsername("test", "sa"): {
  2062. "test": {"policy2": true},
  2063. },
  2064. },
  2065. inPolicies: []*policy.PodSecurityPolicy{
  2066. policyWithName("policy1"),
  2067. policyWithName("policy2"),
  2068. },
  2069. expectValidationErrs: 2,
  2070. },
  2071. }
  2072. for desc, tc := range tests {
  2073. t.Run(desc, func(t *testing.T) {
  2074. authz := &TestAuthorizer{usernameToNamespaceToAllowedPSPs: tc.allowed}
  2075. pod := goodPod()
  2076. pod.Namespace = ns
  2077. pod.Spec.ServiceAccountName = sa
  2078. pod.Spec.SecurityContext.HostPID = true
  2079. plugin := NewTestAdmission(tc.inPolicies, authz)
  2080. attrs := kadmission.NewAttributesRecord(pod, nil, kapi.Kind("Pod").WithVersion("version"), ns, "", kapi.Resource("pods").WithVersion("version"), "", kadmission.Create, &metav1.CreateOptions{}, false, &user.DefaultInfo{Name: userName})
  2081. allowedPod, _, validationErrs, err := plugin.computeSecurityContext(attrs, pod, true, "")
  2082. assert.Nil(t, allowedPod)
  2083. assert.NoError(t, err)
  2084. assert.Len(t, validationErrs, tc.expectValidationErrs)
  2085. })
  2086. }
  2087. }
  2088. func TestPreferValidatedPSP(t *testing.T) {
  2089. restrictivePSPWithName := func(name string) *policy.PodSecurityPolicy {
  2090. p := restrictivePSP()
  2091. p.Name = name
  2092. return p
  2093. }
  2094. permissivePSPWithName := func(name string) *policy.PodSecurityPolicy {
  2095. p := permissivePSP()
  2096. p.Name = name
  2097. return p
  2098. }
  2099. tests := map[string]struct {
  2100. inPolicies []*policy.PodSecurityPolicy
  2101. expectValidationErrs int
  2102. validatedPSPHint string
  2103. expectedPSP string
  2104. }{
  2105. "no policy saved in annotations, PSPs are ordered lexicographically": {
  2106. inPolicies: []*policy.PodSecurityPolicy{
  2107. restrictivePSPWithName("001restrictive"),
  2108. restrictivePSPWithName("002restrictive"),
  2109. permissivePSPWithName("002permissive"),
  2110. permissivePSPWithName("001permissive"),
  2111. permissivePSPWithName("003permissive"),
  2112. },
  2113. expectValidationErrs: 0,
  2114. validatedPSPHint: "",
  2115. expectedPSP: "001permissive",
  2116. },
  2117. "policy saved in annotations is preferred": {
  2118. inPolicies: []*policy.PodSecurityPolicy{
  2119. restrictivePSPWithName("001restrictive"),
  2120. restrictivePSPWithName("002restrictive"),
  2121. permissivePSPWithName("001permissive"),
  2122. permissivePSPWithName("002permissive"),
  2123. permissivePSPWithName("003permissive"),
  2124. },
  2125. expectValidationErrs: 0,
  2126. validatedPSPHint: "002permissive",
  2127. expectedPSP: "002permissive",
  2128. },
  2129. "policy saved in annotations is invalid": {
  2130. inPolicies: []*policy.PodSecurityPolicy{
  2131. restrictivePSPWithName("001restrictive"),
  2132. restrictivePSPWithName("002restrictive"),
  2133. },
  2134. expectValidationErrs: 2,
  2135. validatedPSPHint: "foo",
  2136. expectedPSP: "",
  2137. },
  2138. "policy saved in annotations is disallowed anymore": {
  2139. inPolicies: []*policy.PodSecurityPolicy{
  2140. restrictivePSPWithName("001restrictive"),
  2141. restrictivePSPWithName("002restrictive"),
  2142. },
  2143. expectValidationErrs: 2,
  2144. validatedPSPHint: "001restrictive",
  2145. expectedPSP: "",
  2146. },
  2147. "policy saved in annotations is disallowed anymore, but find another one": {
  2148. inPolicies: []*policy.PodSecurityPolicy{
  2149. restrictivePSPWithName("001restrictive"),
  2150. restrictivePSPWithName("002restrictive"),
  2151. permissivePSPWithName("002permissive"),
  2152. permissivePSPWithName("001permissive"),
  2153. },
  2154. expectValidationErrs: 0,
  2155. validatedPSPHint: "001restrictive",
  2156. expectedPSP: "001permissive",
  2157. },
  2158. }
  2159. for desc, tc := range tests {
  2160. t.Run(desc, func(t *testing.T) {
  2161. authz := authorizerfactory.NewAlwaysAllowAuthorizer()
  2162. allowPrivilegeEscalation := true
  2163. pod := goodPod()
  2164. pod.Namespace = "ns"
  2165. pod.Spec.ServiceAccountName = "sa"
  2166. pod.Spec.Containers[0].SecurityContext.AllowPrivilegeEscalation = &allowPrivilegeEscalation
  2167. plugin := NewTestAdmission(tc.inPolicies, authz)
  2168. attrs := kadmission.NewAttributesRecord(pod, nil, kapi.Kind("Pod").WithVersion("version"), "ns", "", kapi.Resource("pods").WithVersion("version"), "", kadmission.Update, &metav1.UpdateOptions{}, false, &user.DefaultInfo{Name: "test"})
  2169. _, pspName, validationErrs, err := plugin.computeSecurityContext(attrs, pod, false, tc.validatedPSPHint)
  2170. assert.NoError(t, err)
  2171. assert.Len(t, validationErrs, tc.expectValidationErrs)
  2172. assert.Equal(t, tc.expectedPSP, pspName)
  2173. })
  2174. }
  2175. }
  2176. func restrictivePSP() *policy.PodSecurityPolicy {
  2177. allowPrivilegeEscalation := false
  2178. return &policy.PodSecurityPolicy{
  2179. ObjectMeta: metav1.ObjectMeta{
  2180. Name: "restrictive",
  2181. Annotations: map[string]string{},
  2182. },
  2183. Spec: policy.PodSecurityPolicySpec{
  2184. AllowPrivilegeEscalation: &allowPrivilegeEscalation,
  2185. RunAsUser: policy.RunAsUserStrategyOptions{
  2186. Rule: policy.RunAsUserStrategyMustRunAs,
  2187. Ranges: []policy.IDRange{
  2188. {Min: int64(999), Max: int64(999)},
  2189. },
  2190. },
  2191. RunAsGroup: &policy.RunAsGroupStrategyOptions{
  2192. Rule: policy.RunAsGroupStrategyMustRunAs,
  2193. Ranges: []policy.IDRange{
  2194. {Min: int64(999), Max: int64(999)},
  2195. },
  2196. },
  2197. SELinux: policy.SELinuxStrategyOptions{
  2198. Rule: policy.SELinuxStrategyMustRunAs,
  2199. SELinuxOptions: &v1.SELinuxOptions{
  2200. Level: "s9:z0,z1",
  2201. },
  2202. },
  2203. FSGroup: policy.FSGroupStrategyOptions{
  2204. Rule: policy.FSGroupStrategyMustRunAs,
  2205. Ranges: []policy.IDRange{
  2206. {Min: int64(999), Max: int64(999)},
  2207. },
  2208. },
  2209. SupplementalGroups: policy.SupplementalGroupsStrategyOptions{
  2210. Rule: policy.SupplementalGroupsStrategyMustRunAs,
  2211. Ranges: []policy.IDRange{
  2212. {Min: int64(999), Max: int64(999)},
  2213. },
  2214. },
  2215. },
  2216. }
  2217. }
  2218. func permissivePSP() *policy.PodSecurityPolicy {
  2219. allowPrivilegeEscalation := true
  2220. return &policy.PodSecurityPolicy{
  2221. ObjectMeta: metav1.ObjectMeta{
  2222. Name: "privileged",
  2223. Annotations: map[string]string{},
  2224. },
  2225. Spec: policy.PodSecurityPolicySpec{
  2226. AllowPrivilegeEscalation: &allowPrivilegeEscalation,
  2227. HostIPC: true,
  2228. HostNetwork: true,
  2229. HostPID: true,
  2230. HostPorts: []policy.HostPortRange{{Min: 0, Max: 65536}},
  2231. Volumes: []policy.FSType{policy.All},
  2232. AllowedCapabilities: []v1.Capability{policy.AllowAllCapabilities},
  2233. RunAsUser: policy.RunAsUserStrategyOptions{
  2234. Rule: policy.RunAsUserStrategyRunAsAny,
  2235. },
  2236. RunAsGroup: &policy.RunAsGroupStrategyOptions{
  2237. Rule: policy.RunAsGroupStrategyRunAsAny,
  2238. },
  2239. SELinux: policy.SELinuxStrategyOptions{
  2240. Rule: policy.SELinuxStrategyRunAsAny,
  2241. },
  2242. FSGroup: policy.FSGroupStrategyOptions{
  2243. Rule: policy.FSGroupStrategyRunAsAny,
  2244. },
  2245. SupplementalGroups: policy.SupplementalGroupsStrategyOptions{
  2246. Rule: policy.SupplementalGroupsStrategyRunAsAny,
  2247. },
  2248. },
  2249. }
  2250. }
  2251. // goodPod is empty and should not be used directly for testing since we're providing
  2252. // two different PSPs. Since no values are specified it would be allowed to match any
  2253. // psp when defaults are filled in.
  2254. func goodPod() *kapi.Pod {
  2255. return &kapi.Pod{
  2256. ObjectMeta: metav1.ObjectMeta{
  2257. Name: "pod",
  2258. Namespace: "namespace",
  2259. Annotations: map[string]string{},
  2260. },
  2261. Spec: kapi.PodSpec{
  2262. ServiceAccountName: "default",
  2263. SecurityContext: &kapi.PodSecurityContext{},
  2264. Containers: []kapi.Container{
  2265. {
  2266. Name: defaultContainerName,
  2267. SecurityContext: &kapi.SecurityContext{},
  2268. },
  2269. },
  2270. },
  2271. }
  2272. }