handlers.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. /*
  2. Copyright 2014 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 lifecycle
  14. import (
  15. "fmt"
  16. "io/ioutil"
  17. "net"
  18. "net/http"
  19. "strconv"
  20. "k8s.io/api/core/v1"
  21. "k8s.io/apimachinery/pkg/types"
  22. "k8s.io/apimachinery/pkg/util/intstr"
  23. "k8s.io/klog"
  24. kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
  25. kubetypes "k8s.io/kubernetes/pkg/kubelet/types"
  26. "k8s.io/kubernetes/pkg/kubelet/util/format"
  27. "k8s.io/kubernetes/pkg/security/apparmor"
  28. )
  29. type HandlerRunner struct {
  30. httpGetter kubetypes.HttpGetter
  31. commandRunner kubecontainer.ContainerCommandRunner
  32. containerManager podStatusProvider
  33. }
  34. type podStatusProvider interface {
  35. GetPodStatus(uid types.UID, name, namespace string) (*kubecontainer.PodStatus, error)
  36. }
  37. func NewHandlerRunner(httpGetter kubetypes.HttpGetter, commandRunner kubecontainer.ContainerCommandRunner, containerManager podStatusProvider) kubecontainer.HandlerRunner {
  38. return &HandlerRunner{
  39. httpGetter: httpGetter,
  40. commandRunner: commandRunner,
  41. containerManager: containerManager,
  42. }
  43. }
  44. func (hr *HandlerRunner) Run(containerID kubecontainer.ContainerID, pod *v1.Pod, container *v1.Container, handler *v1.Handler) (string, error) {
  45. switch {
  46. case handler.Exec != nil:
  47. var msg string
  48. // TODO(tallclair): Pass a proper timeout value.
  49. output, err := hr.commandRunner.RunInContainer(containerID, handler.Exec.Command, 0)
  50. if err != nil {
  51. msg = fmt.Sprintf("Exec lifecycle hook (%v) for Container %q in Pod %q failed - error: %v, message: %q", handler.Exec.Command, container.Name, format.Pod(pod), err, string(output))
  52. klog.V(1).Infof(msg)
  53. }
  54. return msg, err
  55. case handler.HTTPGet != nil:
  56. msg, err := hr.runHTTPHandler(pod, container, handler)
  57. if err != nil {
  58. msg = fmt.Sprintf("Http lifecycle hook (%s) for Container %q in Pod %q failed - error: %v, message: %q", handler.HTTPGet.Path, container.Name, format.Pod(pod), err, msg)
  59. klog.V(1).Infof(msg)
  60. }
  61. return msg, err
  62. default:
  63. err := fmt.Errorf("Invalid handler: %v", handler)
  64. msg := fmt.Sprintf("Cannot run handler: %v", err)
  65. klog.Errorf(msg)
  66. return msg, err
  67. }
  68. }
  69. // resolvePort attempts to turn an IntOrString port reference into a concrete port number.
  70. // If portReference has an int value, it is treated as a literal, and simply returns that value.
  71. // If portReference is a string, an attempt is first made to parse it as an integer. If that fails,
  72. // an attempt is made to find a port with the same name in the container spec.
  73. // If a port with the same name is found, it's ContainerPort value is returned. If no matching
  74. // port is found, an error is returned.
  75. func resolvePort(portReference intstr.IntOrString, container *v1.Container) (int, error) {
  76. if portReference.Type == intstr.Int {
  77. return portReference.IntValue(), nil
  78. }
  79. portName := portReference.StrVal
  80. port, err := strconv.Atoi(portName)
  81. if err == nil {
  82. return port, nil
  83. }
  84. for _, portSpec := range container.Ports {
  85. if portSpec.Name == portName {
  86. return int(portSpec.ContainerPort), nil
  87. }
  88. }
  89. return -1, fmt.Errorf("couldn't find port: %v in %v", portReference, container)
  90. }
  91. func (hr *HandlerRunner) runHTTPHandler(pod *v1.Pod, container *v1.Container, handler *v1.Handler) (string, error) {
  92. host := handler.HTTPGet.Host
  93. if len(host) == 0 {
  94. status, err := hr.containerManager.GetPodStatus(pod.UID, pod.Name, pod.Namespace)
  95. if err != nil {
  96. klog.Errorf("Unable to get pod info, event handlers may be invalid.")
  97. return "", err
  98. }
  99. if status.IP == "" {
  100. return "", fmt.Errorf("failed to find networking container: %v", status)
  101. }
  102. host = status.IP
  103. }
  104. var port int
  105. if handler.HTTPGet.Port.Type == intstr.String && len(handler.HTTPGet.Port.StrVal) == 0 {
  106. port = 80
  107. } else {
  108. var err error
  109. port, err = resolvePort(handler.HTTPGet.Port, container)
  110. if err != nil {
  111. return "", err
  112. }
  113. }
  114. url := fmt.Sprintf("http://%s/%s", net.JoinHostPort(host, strconv.Itoa(port)), handler.HTTPGet.Path)
  115. resp, err := hr.httpGetter.Get(url)
  116. return getHttpRespBody(resp), err
  117. }
  118. func getHttpRespBody(resp *http.Response) string {
  119. if resp == nil {
  120. return ""
  121. }
  122. defer resp.Body.Close()
  123. if bytes, err := ioutil.ReadAll(resp.Body); err == nil {
  124. return string(bytes)
  125. }
  126. return ""
  127. }
  128. func NewAppArmorAdmitHandler(validator apparmor.Validator) PodAdmitHandler {
  129. return &appArmorAdmitHandler{
  130. Validator: validator,
  131. }
  132. }
  133. type appArmorAdmitHandler struct {
  134. apparmor.Validator
  135. }
  136. func (a *appArmorAdmitHandler) Admit(attrs *PodAdmitAttributes) PodAdmitResult {
  137. // If the pod is already running or terminated, no need to recheck AppArmor.
  138. if attrs.Pod.Status.Phase != v1.PodPending {
  139. return PodAdmitResult{Admit: true}
  140. }
  141. err := a.Validate(attrs.Pod)
  142. if err == nil {
  143. return PodAdmitResult{Admit: true}
  144. }
  145. return PodAdmitResult{
  146. Admit: false,
  147. Reason: "AppArmor",
  148. Message: fmt.Sprintf("Cannot enforce AppArmor: %v", err),
  149. }
  150. }
  151. func NewNoNewPrivsAdmitHandler(runtime kubecontainer.Runtime) PodAdmitHandler {
  152. return &noNewPrivsAdmitHandler{
  153. Runtime: runtime,
  154. }
  155. }
  156. type noNewPrivsAdmitHandler struct {
  157. kubecontainer.Runtime
  158. }
  159. func (a *noNewPrivsAdmitHandler) Admit(attrs *PodAdmitAttributes) PodAdmitResult {
  160. // If the pod is already running or terminated, no need to recheck NoNewPrivs.
  161. if attrs.Pod.Status.Phase != v1.PodPending {
  162. return PodAdmitResult{Admit: true}
  163. }
  164. // If the containers in a pod do not require no-new-privs, admit it.
  165. if !noNewPrivsRequired(attrs.Pod) {
  166. return PodAdmitResult{Admit: true}
  167. }
  168. // Always admit runtimes except docker.
  169. if a.Runtime.Type() != kubetypes.DockerContainerRuntime {
  170. return PodAdmitResult{Admit: true}
  171. }
  172. // Make sure docker api version is valid.
  173. rversion, err := a.Runtime.APIVersion()
  174. if err != nil {
  175. return PodAdmitResult{
  176. Admit: false,
  177. Reason: "NoNewPrivs",
  178. Message: fmt.Sprintf("Cannot enforce NoNewPrivs: %v", err),
  179. }
  180. }
  181. v, err := rversion.Compare("1.23.0")
  182. if err != nil {
  183. return PodAdmitResult{
  184. Admit: false,
  185. Reason: "NoNewPrivs",
  186. Message: fmt.Sprintf("Cannot enforce NoNewPrivs: %v", err),
  187. }
  188. }
  189. // If the version is less than 1.23 it will return -1 above.
  190. if v == -1 {
  191. return PodAdmitResult{
  192. Admit: false,
  193. Reason: "NoNewPrivs",
  194. Message: fmt.Sprintf("Cannot enforce NoNewPrivs: docker runtime API version %q must be greater than or equal to 1.23", rversion.String()),
  195. }
  196. }
  197. return PodAdmitResult{Admit: true}
  198. }
  199. func noNewPrivsRequired(pod *v1.Pod) bool {
  200. // Iterate over pod containers and check if we added no-new-privs.
  201. for _, c := range pod.Spec.Containers {
  202. if c.SecurityContext != nil && c.SecurityContext.AllowPrivilegeEscalation != nil && !*c.SecurityContext.AllowPrivilegeEscalation {
  203. return true
  204. }
  205. }
  206. return false
  207. }
  208. func NewProcMountAdmitHandler(runtime kubecontainer.Runtime) PodAdmitHandler {
  209. return &procMountAdmitHandler{
  210. Runtime: runtime,
  211. }
  212. }
  213. type procMountAdmitHandler struct {
  214. kubecontainer.Runtime
  215. }
  216. func (a *procMountAdmitHandler) Admit(attrs *PodAdmitAttributes) PodAdmitResult {
  217. // If the pod is already running or terminated, no need to recheck NoNewPrivs.
  218. if attrs.Pod.Status.Phase != v1.PodPending {
  219. return PodAdmitResult{Admit: true}
  220. }
  221. // If the containers in a pod only need the default ProcMountType, admit it.
  222. if procMountIsDefault(attrs.Pod) {
  223. return PodAdmitResult{Admit: true}
  224. }
  225. // Always admit runtimes except docker.
  226. if a.Runtime.Type() != kubetypes.DockerContainerRuntime {
  227. return PodAdmitResult{Admit: true}
  228. }
  229. // Make sure docker api version is valid.
  230. // Merged in https://github.com/moby/moby/pull/36644
  231. rversion, err := a.Runtime.APIVersion()
  232. if err != nil {
  233. return PodAdmitResult{
  234. Admit: false,
  235. Reason: "ProcMount",
  236. Message: fmt.Sprintf("Cannot enforce ProcMount: %v", err),
  237. }
  238. }
  239. v, err := rversion.Compare("1.38.0")
  240. if err != nil {
  241. return PodAdmitResult{
  242. Admit: false,
  243. Reason: "ProcMount",
  244. Message: fmt.Sprintf("Cannot enforce ProcMount: %v", err),
  245. }
  246. }
  247. // If the version is less than 1.38 it will return -1 above.
  248. if v == -1 {
  249. return PodAdmitResult{
  250. Admit: false,
  251. Reason: "ProcMount",
  252. Message: fmt.Sprintf("Cannot enforce ProcMount: docker runtime API version %q must be greater than or equal to 1.38", rversion.String()),
  253. }
  254. }
  255. return PodAdmitResult{Admit: true}
  256. }
  257. func procMountIsDefault(pod *v1.Pod) bool {
  258. // Iterate over pod containers and check if we are using the DefaultProcMountType
  259. // for all containers.
  260. for _, c := range pod.Spec.Containers {
  261. if c.SecurityContext != nil {
  262. if c.SecurityContext.ProcMount != nil && *c.SecurityContext.ProcMount != v1.DefaultProcMount {
  263. return false
  264. }
  265. }
  266. }
  267. return true
  268. }