Docker’s out-of-the-box authorization model is all or nothing. But many users require finer-grained access control and Docker’s plugin infrastructure allows us to do so.

This is an excellent opportunity to see how to policy enable an existing service.

Goals

This tutorial helps you get started with OPA and introduces you to core concepts in OPA.

Policy enabling an application decouples the policy implementation from the business logic so that administrators can define policy without changing the application while still keeping up with the size, complexity, and dynamic nature of modern applications.

For the purpose of this tutorial, we want to use OPA to enforce a policy that prevents users from running insecure containers.

This tutorial illustrates two key concepts:

  1. OPA policy definition is decoupled from the implementation of the service (in this case Docker). The administrator is empowered to define and manage policies without requiring changes to any of the apps.

  2. Both the data relevant to policy and the policy definitions themselves can change rapidly.

Prerequisites

This tutorial requires:

  • Docker Engine 18.06.0-ce or newer
  • Docker API version 1.38 or newer
  • root or sudo access
  • Nginx, or any capable bundle server

The tutorial has been tested on the following platforms:

  • Ubuntu 20.04 (64-bit)

If you are using a different distro, OS, or architecture, the steps will be the same. However, there may be slight differences in the commands you need to run.

Steps

Several of the steps below require root or sudo access. When you are modifying files under /etc/docker or signalling the Docker daemon to restart, you will need root access.

1. Create an empty policy definition that will allow all requests.

authz.rego:

  1. package docker.authz
  2. allow := true

This policy defines a single rule named allow that always produces the decision true. Once all the components are running, we will come back to the policy.

2. Create policy bundle and OPA configuration.

For the purpose of this example, we are going to use Nginx to serve bundles from the same machine Docker is running on.

With nginx running, simply build the policy bundle placed into the nginx web root directory.

  1. opa build --bundle --output /var/www/html/bundle.tar.gz .

Next, create an OPA configuration file pointing to the bundle.

  1. services:
  2. authz:
  3. url: http://localhost
  4. bundles:
  5. authz:
  6. service: authz
  7. resource: bundle.tar.gz
  8. # Optional - Print decisions in the Docker logs. Configure a remote service for production use cases.
  9. decision_logs:
  10. console: true

Save the above file as config.yaml. We’ll need to place this somewhere where the plugin can find it. The /etc/docker directory will be mounted as /opa in the container running the plugin, so let’s create a sub-directory for our configuration file there.

  1. sudo mkdir -p /etc/docker/config
  2. sudo mv config.yaml /etc/docker/config/

3. Install the opa-docker-authz plugin.

Install the opa-docker-authz plugin and point it to the config file just created.

  1. docker plugin install openpolicyagent/opa-docker-authz-v2:0.8 opa-args="-config-file /opa/config/config.yaml"

You need to configure the Docker daemon to use the plugin for authorization.

  1. cat > /etc/docker/daemon.json <<EOF
  2. {
  3. "authorization-plugins": ["openpolicyagent/opa-docker-authz-v2:0.8"]
  4. }
  5. EOF

Signal the Docker daemon to reload the configuration file.

  1. kill -HUP $(pidof dockerd)

4. Run a simple Docker command to make sure everything is still working.

  1. docker ps

If everything is set up correctly, the command should exit successfully. You can expect to see log messages from OPA and the plugin.

5. Test that the policy definition is working.

Let’s modify our policy to deny all requests:

authz.rego:

  1. package docker.authz
  2. allow := false

Rebuild the bundle and save it in the Nginx document root directory.

  1. opa build --bundle --output /var/www/html/bundle.tar.gz .

In OPA, rules defines the content of documents. Documents be boolean values (true/false) or they can represent more complex structures using arrays, objects, strings, etc.

In the example above we modified the policy to always return false so that requests will be rejected.

  1. docker ps

The output should be:

  1. Error response from daemon: authorization denied by plugin opa-docker-authz: request rejected by administrative policy

To learn more about how rules define the content of documents, see: How Does OPA Work?

With this policy in place, users will not be able to run any Docker commands. Go ahead and try other commands such as docker run or docker pull. They will all be rejected.

Now let’s change the policy so that it’s a bit more useful.

6. Update the policy to reject requests with the unconfined seccomp profile:

authz.rego:

  1. package docker.authz
  2. default allow = false
  3. allow {
  4. not deny
  5. }
  6. deny {
  7. seccomp_unconfined
  8. }
  9. seccomp_unconfined {
  10. # This expression asserts that the string on the right-hand side is equal
  11. # to an element in the array SecurityOpt referenced on the left-hand side.
  12. input.Body.HostConfig.SecurityOpt[_] == "seccomp:unconfined"
  13. }

Again, rebuild the bundle and save it in the Nginx document root directory.

  1. opa build --bundle --output /var/www/html/bundle.tar.gz .

The plugin queries the allow rule to authorize requests to Docker. The input document is set to the attributes passed from Docker.

  1. allow
  1. {
  2. "AuthMethod": "",
  3. "Body": {
  4. "AttachStderr": true,
  5. "AttachStdin": false,
  6. "AttachStdout": true,
  7. "Cmd": null,
  8. "Domainname": "",
  9. "Entrypoint": null,
  10. "Env": [],
  11. "HostConfig": {
  12. "AutoRemove": false,
  13. "Binds": null,
  14. "BlkioDeviceReadBps": null,
  15. "BlkioDeviceReadIOps": null,
  16. "BlkioDeviceWriteBps": null,
  17. "BlkioDeviceWriteIOps": null,
  18. "BlkioWeight": 0,
  19. "BlkioWeightDevice": [],
  20. "CapAdd": null,
  21. "CapDrop": null,
  22. "Cgroup": "",
  23. "CgroupParent": "",
  24. "ConsoleSize": [
  25. 0,
  26. 0
  27. ],
  28. "ContainerIDFile": "",
  29. "CpuCount": 0,
  30. "CpuPercent": 0,
  31. "CpuPeriod": 0,
  32. "CpuQuota": 0,
  33. "CpuRealtimePeriod": 0,
  34. "CpuRealtimeRuntime": 0,
  35. "CpuShares": 0,
  36. "CpusetCpus": "",
  37. "CpusetMems": "",
  38. "DeviceCgroupRules": null,
  39. "Devices": [],
  40. "DiskQuota": 0,
  41. "Dns": [],
  42. "DnsOptions": [],
  43. "DnsSearch": [],
  44. "ExtraHosts": null,
  45. "GroupAdd": null,
  46. "IOMaximumBandwidth": 0,
  47. "IOMaximumIOps": 0,
  48. "IpcMode": "",
  49. "Isolation": "",
  50. "KernelMemory": 0,
  51. "Links": null,
  52. "LogConfig": {
  53. "Config": {},
  54. "Type": ""
  55. },
  56. "MaskedPaths": null,
  57. "Memory": 0,
  58. "MemoryReservation": 0,
  59. "MemorySwap": 0,
  60. "MemorySwappiness": -1,
  61. "NanoCpus": 0,
  62. "NetworkMode": "default",
  63. "OomKillDisable": false,
  64. "OomScoreAdj": 0,
  65. "PidMode": "",
  66. "PidsLimit": 0,
  67. "PortBindings": {},
  68. "Privileged": false,
  69. "PublishAllPorts": false,
  70. "ReadonlyPaths": null,
  71. "ReadonlyRootfs": false,
  72. "RestartPolicy": {
  73. "MaximumRetryCount": 0,
  74. "Name": "no"
  75. },
  76. "SecurityOpt": null,
  77. "ShmSize": 0,
  78. "UTSMode": "",
  79. "Ulimits": null,
  80. "UsernsMode": "",
  81. "VolumeDriver": "",
  82. "VolumesFrom": null
  83. },
  84. "Hostname": "",
  85. "Image": "hello-world",
  86. "Labels": {},
  87. "NetworkingConfig": {
  88. "EndpointsConfig": {}
  89. },
  90. "OnBuild": null,
  91. "OpenStdin": false,
  92. "StdinOnce": false,
  93. "Tty": false,
  94. "User": "",
  95. "Volumes": {},
  96. "WorkingDir": ""
  97. },
  98. "Headers": {
  99. "Content-Length": "1470",
  100. "Content-Type": "application/json",
  101. "User-Agent": "Docker-Client/18.06.1-ce (linux)"
  102. },
  103. "Method": "POST",
  104. "Path": "/v1.38/containers/create",
  105. "User": ""
  106. }

For the input above, the value of allow is:

  1. true

Many of the examples in the documentation are interactive. Try editing the input above by setting Body.HostConfig.SecurityOpt to ["seccomp:unconfined"].

7. Test the policy is working by running a simple container:

  1. docker run hello-world

Now try running the same container but disable seccomp (which should be prevented by the policy):

  1. docker run --security-opt seccomp:unconfined hello-world

Congratulations! You have successfully prevented containers from running without seccomp!

The rest of the tutorial shows how you can grant fine-grained access to specific clients.

8. Identify the user in Docker requests.

Back up your existing Docker configuration, just in case. You can replace your original configuration after you are done with the tutorial.

  1. mkdir -p ~/.docker
  2. cp ~/.docker/config.json ~/.docker/config.json~

To identify the user, include an HTTP header in all of the requests sent to the Docker daemon:

  1. cat >~/.docker/config.json <<EOF
  2. {
  3. "HttpHeaders": {
  4. "Authz-User": "bob"
  5. }
  6. }
  7. EOF

Docker does not currently provide a way to authenticate clients. But in Docker 1.12, clients can be authenticated using TLS and there are plans to include other means of authentication. For the purpose of this tutorial, we assume that an authentication system is place.

9. Update the policy to include basic user access controls.

  1. package docker.authz
  2. default allow := false
  3. # allow if the user is granted read/write access.
  4. allow {
  5. user_id := input.Headers["Authz-User"]
  6. user := users[user_id]
  7. not user.readOnly
  8. }
  9. # allow if the user is granted read-only access and the request is a GET.
  10. allow {
  11. user_id := input.Headers["Authz-User"]
  12. users[user_id].readOnly
  13. input.Method == "GET"
  14. }
  15. # users defines permissions for the user. In this case, we define a single
  16. # attribute 'readOnly' that controls the kinds of commands the user can run.
  17. users := {
  18. "bob": {"readOnly": true},
  19. "alice": {"readOnly": false},
  20. }

10. Attempt to run a container.

Because the configured user is "bob", the request is rejected:

  1. docker run hello-world

11. Change the user to “alice” and re-run the container.

  1. cat > ~/.docker/config.json <<EOF
  2. {
  3. "HttpHeaders": {
  4. "Authz-User": "alice"
  5. }
  6. }
  7. EOF

Because the configured user is "alice", the request will succeed:

  1. docker run hello-world

That’s it!