Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an option to add and drop capabilities in the Docker driver #3754

Merged
merged 7 commits into from
Jan 23, 2018
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions client/driver/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"github.com/docker/docker/cli/config/configfile"
"github.com/docker/docker/reference"
"github.com/docker/docker/registry"
"github.com/moby/moby/daemon/caps"

"github.com/hashicorp/go-multierror"
"github.com/hashicorp/go-plugin"
Expand Down Expand Up @@ -99,6 +100,9 @@ const (
dockerImageRemoveDelayConfigOption = "docker.cleanup.image.delay"
dockerImageRemoveDelayConfigDefault = 3 * time.Minute

dockerCapsWhitelistConfigOption = "docker.caps.whitelist"
dockerCapsWhitelistConfigDefault = dockerBasicCaps
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add a comment documenting these


// dockerTimeout is the length of time a request can be outstanding before
// it is timed out.
dockerTimeout = 5 * time.Minute
Expand All @@ -109,6 +113,9 @@ const (
// dockerAuthHelperPrefix is the prefix to attach to the credential helper
// and should be found in the $PATH. Example: ${prefix-}${helper-name}
dockerAuthHelperPrefix = "docker-credential-"

dockerBasicCaps = "CHOWN,DAC_OVERRIDE,FSETID,FOWNER,MKNOD," +
"NET_RAW,SETGID,SETUID,SETFCAP,SETPCAP,NET_BIND_SERVICE,SYS_CHROOT,KILL,AUDIT_WRITE"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a comment documenting what this is for and how the options were chosen

)

type DockerDriver struct {
Expand Down Expand Up @@ -202,6 +209,8 @@ type DockerDriverConfig struct {
MacAddress string `mapstructure:"mac_address"` // Pin mac address to container
SecurityOpt []string `mapstructure:"security_opt"` // Flags to pass directly to security-opt
Devices []DockerDevice `mapstructure:"devices"` // To allow mounting USB or other serial control devices
CapAdd []string `mapstructure:"cap_add"` // Flags to pass directly to cap-add
CapDrop []string `mapstructure:"cap_drop"` // Flags to pass directly to cap-drop
}

func sliceMergeUlimit(ulimitsRaw map[string]string) ([]docker.ULimit, error) {
Expand Down Expand Up @@ -304,6 +313,8 @@ func NewDockerDriverConfig(task *structs.Task, env *env.TaskEnv) (*DockerDriverC
dconf.ExtraHosts = env.ParseAndReplace(dconf.ExtraHosts)
dconf.MacAddress = env.ReplaceEnv(dconf.MacAddress)
dconf.SecurityOpt = env.ParseAndReplace(dconf.SecurityOpt)
dconf.CapAdd = env.ParseAndReplace(dconf.CapAdd)
dconf.CapDrop = env.ParseAndReplace(dconf.CapDrop)

for _, m := range dconf.SysctlRaw {
for k, v := range m {
Expand Down Expand Up @@ -644,6 +655,12 @@ func (d *DockerDriver) Validate(config map[string]interface{}) error {
"devices": {
Type: fields.TypeArray,
},
"cap_add": {
Type: fields.TypeArray,
},
"cap_drop": {
Type: fields.TypeArray,
},
},
}

Expand Down Expand Up @@ -1115,6 +1132,32 @@ func (d *DockerDriver) createContainerConfig(ctx *ExecContext, task *structs.Tas
}
hostConfig.Privileged = driverConfig.Privileged

// set capabilities
hostCapsWhitelist := d.config.ReadDefault(dockerCapsWhitelistConfigOption, dockerCapsWhitelistConfigDefault)
hostCapsWhitelist = strings.ToLower(hostCapsWhitelist)
if !strings.Contains(hostCapsWhitelist, "all") {
effectiveCaps, err := caps.TweakCapabilities(
strings.Split(dockerBasicCaps, ","),
driverConfig.CapAdd,
driverConfig.CapDrop,
)
if err != nil {
return c, err
}
var missingCaps []string
for _, cap := range effectiveCaps {
cap = strings.ToLower(cap[len("CAP_"):])
if !strings.Contains(hostCapsWhitelist, cap) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This logic is susceptible to imprecise substring matches. Despite no existing capability being a substring of another capability, I still feel like this risks a future exploit by allowing "admin" to match "net_admin" in the whitelist.

Can we either parse the cap whitelist into a map to do key lookups or surround the whitelist with delimiters (,) and search for the delimited form: ,net_admin,.

I know capabilities don't change often (ever anymore?), but I'd still rather be safe than sorry when doing any sort of whitelist lookups.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh yeah, absolutely :) This is just a quick poc to get some feedback. I'll try finish this over the weekend.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great! Yeah, your general approach looks great.

missingCaps = append(missingCaps, cap)
}
}
if len(missingCaps) > 0 {
return c, fmt.Errorf("Docker driver doesn't have the following caps whitelisted on this Nomad agent: %s", missingCaps)
}
}
hostConfig.CapAdd = driverConfig.CapAdd
hostConfig.CapDrop = driverConfig.CapDrop

// set SHM size
if driverConfig.ShmSize != 0 {
hostConfig.ShmSize = driverConfig.ShmSize
Expand Down
31 changes: 31 additions & 0 deletions client/driver/docker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1048,6 +1048,37 @@ func TestDockerDriver_SecurityOpt(t *testing.T) {
}
}

func TestDockerDriver_Capabilities(t *testing.T) {
if !tu.IsTravis() {
t.Parallel()
}
if !testutil.DockerIsConnected(t) {
t.Skip("Docker not connected")
}

task, _, _ := dockerTask(t)
task.Config["cap_add"] = []string{"ALL"}
task.Config["cap_drop"] = []string{"MKNOD", "NET_ADMIN"}

client, handle, cleanup := dockerSetup(t, task)
defer cleanup()

waitForExist(t, client, handle)

container, err := client.InspectContainer(handle.ContainerID())
if err != nil {
t.Fatalf("err: %v", err)
}

if !reflect.DeepEqual(task.Config["cap_add"], container.HostConfig.CapAdd) {
t.Errorf("CapAdd doesn't match.\nExpected:\n%s\nGot:\n%s\n", task.Config["cap_add"], container.HostConfig.CapAdd)
}

if !reflect.DeepEqual(task.Config["cap_drop"], container.HostConfig.CapDrop) {
t.Errorf("CapDrop doesn't match.\nExpected:\n%s\nGot:\n%s\n", task.Config["cap_drop"], container.HostConfig.CapDrop)
}
}

func TestDockerDriver_DNS(t *testing.T) {
if !tu.IsTravis() {
t.Parallel()
Expand Down
26 changes: 26 additions & 0 deletions website/source/docs/drivers/docker.html.md
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,32 @@ The `docker` driver supports the following configuration in the job spec. Only
}
```

* `cap_add` - (Optional) A list of string flags to pass directly to
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A list of Linux capabilities as strings to pass directly to . Only whitelisted capabilities may be added. The whitelist can be customized using the docker.caps.whitelist key in the client node's configuration.

And then make sure to document docker.caps.whitelist too.

Note you don't need to use the exact text I wrote. Just make sure to mention the whitelist and the word capabilities just in case someone is searching for that particular word. :)

[`--cap-add`](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities).
For example:


```hcl
config {
cap_add = [
"SYS_TIME",
]
}
```

* `cap_drop` - (Optional) A list of string flags to pass directly to
[`--cap-drop`](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities).
For example:


```hcl
config {
cap_drop = [
"MKNOD",
]
}
```

### Container Name

Nomad creates a container after pulling an image. Containers are named
Expand Down