pods.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. /*
  2. Copyright 2018 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 webhook
  14. import (
  15. "fmt"
  16. "strings"
  17. "k8s.io/api/admission/v1"
  18. corev1 "k8s.io/api/core/v1"
  19. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. "k8s.io/klog"
  21. )
  22. const (
  23. podsInitContainerPatch string = `[
  24. {"op":"add","path":"/spec/initContainers","value":[{"image":"webhook-added-image","name":"webhook-added-init-container","resources":{}}]}
  25. ]`
  26. podsSidecarPatch string = `[
  27. {"op":"add", "path":"/spec/containers/-","value":{"image":"%v","name":"webhook-added-sidecar","resources":{}}}
  28. ]`
  29. )
  30. // only allow pods to pull images from specific registry.
  31. func admitPods(ar v1.AdmissionReview) *v1.AdmissionResponse {
  32. klog.V(2).Info("admitting pods")
  33. podResource := metav1.GroupVersionResource{Group: "", Version: "v1", Resource: "pods"}
  34. if ar.Request.Resource != podResource {
  35. err := fmt.Errorf("expect resource to be %s", podResource)
  36. klog.Error(err)
  37. return toV1AdmissionResponse(err)
  38. }
  39. raw := ar.Request.Object.Raw
  40. pod := corev1.Pod{}
  41. deserializer := codecs.UniversalDeserializer()
  42. if _, _, err := deserializer.Decode(raw, nil, &pod); err != nil {
  43. klog.Error(err)
  44. return toV1AdmissionResponse(err)
  45. }
  46. reviewResponse := v1.AdmissionResponse{}
  47. reviewResponse.Allowed = true
  48. var msg string
  49. if v, ok := pod.Labels["webhook-e2e-test"]; ok {
  50. if v == "webhook-disallow" {
  51. reviewResponse.Allowed = false
  52. msg = msg + "the pod contains unwanted label; "
  53. }
  54. if v == "wait-forever" {
  55. reviewResponse.Allowed = false
  56. msg = msg + "the pod response should not be sent; "
  57. <-make(chan int) // Sleep forever - no one sends to this channel
  58. }
  59. }
  60. for _, container := range pod.Spec.Containers {
  61. if strings.Contains(container.Name, "webhook-disallow") {
  62. reviewResponse.Allowed = false
  63. msg = msg + "the pod contains unwanted container name; "
  64. }
  65. }
  66. if !reviewResponse.Allowed {
  67. reviewResponse.Result = &metav1.Status{Message: strings.TrimSpace(msg)}
  68. }
  69. return &reviewResponse
  70. }
  71. func mutatePods(ar v1.AdmissionReview) *v1.AdmissionResponse {
  72. shouldPatchPod := func(pod *corev1.Pod) bool {
  73. if pod.Name != "webhook-to-be-mutated" {
  74. return false
  75. }
  76. return !hasContainer(pod.Spec.InitContainers, "webhook-added-init-container")
  77. }
  78. return applyPodPatch(ar, shouldPatchPod, podsInitContainerPatch)
  79. }
  80. func mutatePodsSidecar(ar v1.AdmissionReview) *v1.AdmissionResponse {
  81. if sidecarImage == "" {
  82. return &v1.AdmissionResponse{
  83. Allowed: false,
  84. Result: &metav1.Status{
  85. Status: "Failure",
  86. Message: "No image specified by the sidecar-image parameter",
  87. Code: 500,
  88. },
  89. }
  90. }
  91. shouldPatchPod := func(pod *corev1.Pod) bool {
  92. return !hasContainer(pod.Spec.Containers, "webhook-added-sidecar")
  93. }
  94. return applyPodPatch(ar, shouldPatchPod, fmt.Sprintf(podsSidecarPatch, sidecarImage))
  95. }
  96. func hasContainer(containers []corev1.Container, containerName string) bool {
  97. for _, container := range containers {
  98. if container.Name == containerName {
  99. return true
  100. }
  101. }
  102. return false
  103. }
  104. func applyPodPatch(ar v1.AdmissionReview, shouldPatchPod func(*corev1.Pod) bool, patch string) *v1.AdmissionResponse {
  105. klog.V(2).Info("mutating pods")
  106. podResource := metav1.GroupVersionResource{Group: "", Version: "v1", Resource: "pods"}
  107. if ar.Request.Resource != podResource {
  108. klog.Errorf("expect resource to be %s", podResource)
  109. return nil
  110. }
  111. raw := ar.Request.Object.Raw
  112. pod := corev1.Pod{}
  113. deserializer := codecs.UniversalDeserializer()
  114. if _, _, err := deserializer.Decode(raw, nil, &pod); err != nil {
  115. klog.Error(err)
  116. return toV1AdmissionResponse(err)
  117. }
  118. reviewResponse := v1.AdmissionResponse{}
  119. reviewResponse.Allowed = true
  120. if shouldPatchPod(&pod) {
  121. reviewResponse.Patch = []byte(patch)
  122. pt := v1.PatchTypeJSONPatch
  123. reviewResponse.PatchType = &pt
  124. }
  125. return &reviewResponse
  126. }
  127. // denySpecificAttachment denies `kubectl attach to-be-attached-pod -i -c=container1"
  128. // or equivalent client requests.
  129. func denySpecificAttachment(ar v1.AdmissionReview) *v1.AdmissionResponse {
  130. klog.V(2).Info("handling attaching pods")
  131. if ar.Request.Name != "to-be-attached-pod" {
  132. return &v1.AdmissionResponse{Allowed: true}
  133. }
  134. podResource := metav1.GroupVersionResource{Group: "", Version: "v1", Resource: "pods"}
  135. if e, a := podResource, ar.Request.Resource; e != a {
  136. err := fmt.Errorf("expect resource to be %s, got %s", e, a)
  137. klog.Error(err)
  138. return toV1AdmissionResponse(err)
  139. }
  140. if e, a := "attach", ar.Request.SubResource; e != a {
  141. err := fmt.Errorf("expect subresource to be %s, got %s", e, a)
  142. klog.Error(err)
  143. return toV1AdmissionResponse(err)
  144. }
  145. raw := ar.Request.Object.Raw
  146. podAttachOptions := corev1.PodAttachOptions{}
  147. deserializer := codecs.UniversalDeserializer()
  148. if _, _, err := deserializer.Decode(raw, nil, &podAttachOptions); err != nil {
  149. klog.Error(err)
  150. return toV1AdmissionResponse(err)
  151. }
  152. klog.V(2).Info(fmt.Sprintf("podAttachOptions=%#v\n", podAttachOptions))
  153. if !podAttachOptions.Stdin || podAttachOptions.Container != "container1" {
  154. return &v1.AdmissionResponse{Allowed: true}
  155. }
  156. return &v1.AdmissionResponse{
  157. Allowed: false,
  158. Result: &metav1.Status{
  159. Message: "attaching to pod 'to-be-attached-pod' is not allowed",
  160. },
  161. }
  162. }