config.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. package configs
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "os/exec"
  7. "time"
  8. "github.com/opencontainers/runtime-spec/specs-go"
  9. "github.com/sirupsen/logrus"
  10. )
  11. type Rlimit struct {
  12. Type int `json:"type"`
  13. Hard uint64 `json:"hard"`
  14. Soft uint64 `json:"soft"`
  15. }
  16. // IDMap represents UID/GID Mappings for User Namespaces.
  17. type IDMap struct {
  18. ContainerID int `json:"container_id"`
  19. HostID int `json:"host_id"`
  20. Size int `json:"size"`
  21. }
  22. // Seccomp represents syscall restrictions
  23. // By default, only the native architecture of the kernel is allowed to be used
  24. // for syscalls. Additional architectures can be added by specifying them in
  25. // Architectures.
  26. type Seccomp struct {
  27. DefaultAction Action `json:"default_action"`
  28. Architectures []string `json:"architectures"`
  29. Syscalls []*Syscall `json:"syscalls"`
  30. }
  31. // Action is taken upon rule match in Seccomp
  32. type Action int
  33. const (
  34. Kill Action = iota + 1
  35. Errno
  36. Trap
  37. Allow
  38. Trace
  39. )
  40. // Operator is a comparison operator to be used when matching syscall arguments in Seccomp
  41. type Operator int
  42. const (
  43. EqualTo Operator = iota + 1
  44. NotEqualTo
  45. GreaterThan
  46. GreaterThanOrEqualTo
  47. LessThan
  48. LessThanOrEqualTo
  49. MaskEqualTo
  50. )
  51. // Arg is a rule to match a specific syscall argument in Seccomp
  52. type Arg struct {
  53. Index uint `json:"index"`
  54. Value uint64 `json:"value"`
  55. ValueTwo uint64 `json:"value_two"`
  56. Op Operator `json:"op"`
  57. }
  58. // Syscall is a rule to match a syscall in Seccomp
  59. type Syscall struct {
  60. Name string `json:"name"`
  61. Action Action `json:"action"`
  62. Args []*Arg `json:"args"`
  63. }
  64. // TODO Windows. Many of these fields should be factored out into those parts
  65. // which are common across platforms, and those which are platform specific.
  66. // Config defines configuration options for executing a process inside a contained environment.
  67. type Config struct {
  68. // NoPivotRoot will use MS_MOVE and a chroot to jail the process into the container's rootfs
  69. // This is a common option when the container is running in ramdisk
  70. NoPivotRoot bool `json:"no_pivot_root"`
  71. // ParentDeathSignal specifies the signal that is sent to the container's process in the case
  72. // that the parent process dies.
  73. ParentDeathSignal int `json:"parent_death_signal"`
  74. // Path to a directory containing the container's root filesystem.
  75. Rootfs string `json:"rootfs"`
  76. // Readonlyfs will remount the container's rootfs as readonly where only externally mounted
  77. // bind mounts are writtable.
  78. Readonlyfs bool `json:"readonlyfs"`
  79. // Specifies the mount propagation flags to be applied to /.
  80. RootPropagation int `json:"rootPropagation"`
  81. // Mounts specify additional source and destination paths that will be mounted inside the container's
  82. // rootfs and mount namespace if specified
  83. Mounts []*Mount `json:"mounts"`
  84. // The device nodes that should be automatically created within the container upon container start. Note, make sure that the node is marked as allowed in the cgroup as well!
  85. Devices []*Device `json:"devices"`
  86. MountLabel string `json:"mount_label"`
  87. // Hostname optionally sets the container's hostname if provided
  88. Hostname string `json:"hostname"`
  89. // Namespaces specifies the container's namespaces that it should setup when cloning the init process
  90. // If a namespace is not provided that namespace is shared from the container's parent process
  91. Namespaces Namespaces `json:"namespaces"`
  92. // Capabilities specify the capabilities to keep when executing the process inside the container
  93. // All capabilities not specified will be dropped from the processes capability mask
  94. Capabilities *Capabilities `json:"capabilities"`
  95. // Networks specifies the container's network setup to be created
  96. Networks []*Network `json:"networks"`
  97. // Routes can be specified to create entries in the route table as the container is started
  98. Routes []*Route `json:"routes"`
  99. // Cgroups specifies specific cgroup settings for the various subsystems that the container is
  100. // placed into to limit the resources the container has available
  101. Cgroups *Cgroup `json:"cgroups"`
  102. // AppArmorProfile specifies the profile to apply to the process running in the container and is
  103. // change at the time the process is execed
  104. AppArmorProfile string `json:"apparmor_profile,omitempty"`
  105. // ProcessLabel specifies the label to apply to the process running in the container. It is
  106. // commonly used by selinux
  107. ProcessLabel string `json:"process_label,omitempty"`
  108. // Rlimits specifies the resource limits, such as max open files, to set in the container
  109. // If Rlimits are not set, the container will inherit rlimits from the parent process
  110. Rlimits []Rlimit `json:"rlimits,omitempty"`
  111. // OomScoreAdj specifies the adjustment to be made by the kernel when calculating oom scores
  112. // for a process. Valid values are between the range [-1000, '1000'], where processes with
  113. // higher scores are preferred for being killed. If it is unset then we don't touch the current
  114. // value.
  115. // More information about kernel oom score calculation here: https://lwn.net/Articles/317814/
  116. OomScoreAdj *int `json:"oom_score_adj,omitempty"`
  117. // UidMappings is an array of User ID mappings for User Namespaces
  118. UidMappings []IDMap `json:"uid_mappings"`
  119. // GidMappings is an array of Group ID mappings for User Namespaces
  120. GidMappings []IDMap `json:"gid_mappings"`
  121. // MaskPaths specifies paths within the container's rootfs to mask over with a bind
  122. // mount pointing to /dev/null as to prevent reads of the file.
  123. MaskPaths []string `json:"mask_paths"`
  124. // ReadonlyPaths specifies paths within the container's rootfs to remount as read-only
  125. // so that these files prevent any writes.
  126. ReadonlyPaths []string `json:"readonly_paths"`
  127. // Sysctl is a map of properties and their values. It is the equivalent of using
  128. // sysctl -w my.property.name value in Linux.
  129. Sysctl map[string]string `json:"sysctl"`
  130. // Seccomp allows actions to be taken whenever a syscall is made within the container.
  131. // A number of rules are given, each having an action to be taken if a syscall matches it.
  132. // A default action to be taken if no rules match is also given.
  133. Seccomp *Seccomp `json:"seccomp"`
  134. // NoNewPrivileges controls whether processes in the container can gain additional privileges.
  135. NoNewPrivileges bool `json:"no_new_privileges,omitempty"`
  136. // Hooks are a collection of actions to perform at various container lifecycle events.
  137. // CommandHooks are serialized to JSON, but other hooks are not.
  138. Hooks *Hooks
  139. // Version is the version of opencontainer specification that is supported.
  140. Version string `json:"version"`
  141. // Labels are user defined metadata that is stored in the config and populated on the state
  142. Labels []string `json:"labels"`
  143. // NoNewKeyring will not allocated a new session keyring for the container. It will use the
  144. // callers keyring in this case.
  145. NoNewKeyring bool `json:"no_new_keyring"`
  146. // IntelRdt specifies settings for Intel RDT group that the container is placed into
  147. // to limit the resources (e.g., L3 cache, memory bandwidth) the container has available
  148. IntelRdt *IntelRdt `json:"intel_rdt,omitempty"`
  149. // RootlessEUID is set when the runc was launched with non-zero EUID.
  150. // Note that RootlessEUID is set to false when launched with EUID=0 in userns.
  151. // When RootlessEUID is set, runc creates a new userns for the container.
  152. // (config.json needs to contain userns settings)
  153. RootlessEUID bool `json:"rootless_euid,omitempty"`
  154. // RootlessCgroups is set when unlikely to have the full access to cgroups.
  155. // When RootlessCgroups is set, cgroups errors are ignored.
  156. RootlessCgroups bool `json:"rootless_cgroups,omitempty"`
  157. }
  158. type Hooks struct {
  159. // Prestart commands are executed after the container namespaces are created,
  160. // but before the user supplied command is executed from init.
  161. Prestart []Hook
  162. // Poststart commands are executed after the container init process starts.
  163. Poststart []Hook
  164. // Poststop commands are executed after the container init process exits.
  165. Poststop []Hook
  166. }
  167. type Capabilities struct {
  168. // Bounding is the set of capabilities checked by the kernel.
  169. Bounding []string
  170. // Effective is the set of capabilities checked by the kernel.
  171. Effective []string
  172. // Inheritable is the capabilities preserved across execve.
  173. Inheritable []string
  174. // Permitted is the limiting superset for effective capabilities.
  175. Permitted []string
  176. // Ambient is the ambient set of capabilities that are kept.
  177. Ambient []string
  178. }
  179. func (hooks *Hooks) UnmarshalJSON(b []byte) error {
  180. var state struct {
  181. Prestart []CommandHook
  182. Poststart []CommandHook
  183. Poststop []CommandHook
  184. }
  185. if err := json.Unmarshal(b, &state); err != nil {
  186. return err
  187. }
  188. deserialize := func(shooks []CommandHook) (hooks []Hook) {
  189. for _, shook := range shooks {
  190. hooks = append(hooks, shook)
  191. }
  192. return hooks
  193. }
  194. hooks.Prestart = deserialize(state.Prestart)
  195. hooks.Poststart = deserialize(state.Poststart)
  196. hooks.Poststop = deserialize(state.Poststop)
  197. return nil
  198. }
  199. func (hooks Hooks) MarshalJSON() ([]byte, error) {
  200. serialize := func(hooks []Hook) (serializableHooks []CommandHook) {
  201. for _, hook := range hooks {
  202. switch chook := hook.(type) {
  203. case CommandHook:
  204. serializableHooks = append(serializableHooks, chook)
  205. default:
  206. logrus.Warnf("cannot serialize hook of type %T, skipping", hook)
  207. }
  208. }
  209. return serializableHooks
  210. }
  211. return json.Marshal(map[string]interface{}{
  212. "prestart": serialize(hooks.Prestart),
  213. "poststart": serialize(hooks.Poststart),
  214. "poststop": serialize(hooks.Poststop),
  215. })
  216. }
  217. // HookState is the payload provided to a hook on execution.
  218. type HookState specs.State
  219. type Hook interface {
  220. // Run executes the hook with the provided state.
  221. Run(HookState) error
  222. }
  223. // NewFunctionHook will call the provided function when the hook is run.
  224. func NewFunctionHook(f func(HookState) error) FuncHook {
  225. return FuncHook{
  226. run: f,
  227. }
  228. }
  229. type FuncHook struct {
  230. run func(HookState) error
  231. }
  232. func (f FuncHook) Run(s HookState) error {
  233. return f.run(s)
  234. }
  235. type Command struct {
  236. Path string `json:"path"`
  237. Args []string `json:"args"`
  238. Env []string `json:"env"`
  239. Dir string `json:"dir"`
  240. Timeout *time.Duration `json:"timeout"`
  241. }
  242. // NewCommandHook will execute the provided command when the hook is run.
  243. func NewCommandHook(cmd Command) CommandHook {
  244. return CommandHook{
  245. Command: cmd,
  246. }
  247. }
  248. type CommandHook struct {
  249. Command
  250. }
  251. func (c Command) Run(s HookState) error {
  252. b, err := json.Marshal(s)
  253. if err != nil {
  254. return err
  255. }
  256. var stdout, stderr bytes.Buffer
  257. cmd := exec.Cmd{
  258. Path: c.Path,
  259. Args: c.Args,
  260. Env: c.Env,
  261. Stdin: bytes.NewReader(b),
  262. Stdout: &stdout,
  263. Stderr: &stderr,
  264. }
  265. if err := cmd.Start(); err != nil {
  266. return err
  267. }
  268. errC := make(chan error, 1)
  269. go func() {
  270. err := cmd.Wait()
  271. if err != nil {
  272. err = fmt.Errorf("error running hook: %v, stdout: %s, stderr: %s", err, stdout.String(), stderr.String())
  273. }
  274. errC <- err
  275. }()
  276. var timerCh <-chan time.Time
  277. if c.Timeout != nil {
  278. timer := time.NewTimer(*c.Timeout)
  279. defer timer.Stop()
  280. timerCh = timer.C
  281. }
  282. select {
  283. case err := <-errC:
  284. return err
  285. case <-timerCh:
  286. cmd.Process.Kill()
  287. cmd.Wait()
  288. return fmt.Errorf("hook ran past specified timeout of %.1fs", c.Timeout.Seconds())
  289. }
  290. }