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

Docker authorization plug-in infrastructure #15365

Merged
merged 6 commits into from
Dec 12, 2015
Merged
Show file tree
Hide file tree
Changes from all 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
35 changes: 35 additions & 0 deletions api/server/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/docker/docker/api/server/httputils"
"github.com/docker/docker/dockerversion"
"github.com/docker/docker/errors"
"github.com/docker/docker/pkg/authorization"
"github.com/docker/docker/pkg/version"
"golang.org/x/net/context"
)
Expand Down Expand Up @@ -47,6 +48,35 @@ func debugRequestMiddleware(handler httputils.APIFunc) httputils.APIFunc {
}
}

// authorizationMiddleware perform authorization on the request.
func (s *Server) authorizationMiddleware(handler httputils.APIFunc) httputils.APIFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
// User and UserAuthNMethod are taken from AuthN plugins
// Currently tracked in https://github.com/docker/docker/pull/13994
user := ""
userAuthNMethod := ""
authCtx := authorization.NewCtx(s.authZPlugins, user, userAuthNMethod, r.Method, r.RequestURI)

if err := authCtx.AuthZRequest(w, r); err != nil {
logrus.Errorf("AuthZRequest for %s %s returned error: %s", r.Method, r.RequestURI, err)
return err
}

rw := authorization.NewResponseModifier(w)

if err := handler(ctx, rw, r, vars); err != nil {
logrus.Errorf("Handler for %s %s returned error: %s", r.Method, r.RequestURI, err)
return err
}

if err := authCtx.AuthZResponse(rw, r); err != nil {
logrus.Errorf("AuthZResponse for %s %s returned error: %s", r.Method, r.RequestURI, err)
return err
}
return nil
}
}

// userAgentMiddleware checks the User-Agent header looking for a valid docker client spec.
func (s *Server) userAgentMiddleware(handler httputils.APIFunc) httputils.APIFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
Expand Down Expand Up @@ -133,6 +163,11 @@ func (s *Server) handleWithGlobalMiddlewares(handler httputils.APIFunc) httputil
middlewares = append(middlewares, debugRequestMiddleware)
}

if len(s.cfg.AuthZPluginNames) > 0 {
s.authZPlugins = authorization.NewPlugins(s.cfg.AuthZPluginNames)
middlewares = append(middlewares, s.authorizationMiddleware)
}

h := handler
for _, m := range middlewares {
h = m(h)
Expand Down
23 changes: 13 additions & 10 deletions api/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/docker/docker/api/server/router/system"
"github.com/docker/docker/api/server/router/volume"
"github.com/docker/docker/daemon"
"github.com/docker/docker/pkg/authorization"
"github.com/docker/docker/pkg/sockets"
"github.com/docker/docker/utils"
"github.com/gorilla/mux"
Expand All @@ -28,20 +29,22 @@ const versionMatcher = "/v{version:[0-9.]+}"

// Config provides the configuration for the API server
type Config struct {
Logging bool
EnableCors bool
CorsHeaders string
Version string
SocketGroup string
TLSConfig *tls.Config
Addrs []Addr
Logging bool
EnableCors bool
CorsHeaders string
AuthZPluginNames []string
Version string
SocketGroup string
TLSConfig *tls.Config
Addrs []Addr
}

// Server contains instance details for the server
type Server struct {
cfg *Config
servers []*HTTPServer
routers []router.Router
cfg *Config
servers []*HTTPServer
routers []router.Router
authZPlugins []authorization.Plugin
}

// Addr contains string representation of address and its protocol (tcp, unix...).
Expand Down
2 changes: 2 additions & 0 deletions daemon/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const (
// CommonConfig defines the configuration of a docker daemon which are
// common across platforms.
type CommonConfig struct {
AuthZPlugins []string // AuthZPlugins holds list of authorization plugins
AutoRestart bool
Bridge bridgeConfig // Bridge holds bridge network specific configuration.
Context map[string][]string
Expand Down Expand Up @@ -54,6 +55,7 @@ type CommonConfig struct {
// from the command-line.
func (config *Config) InstallCommonFlags(cmd *flag.FlagSet, usageFn func(string) string) {
cmd.Var(opts.NewListOptsRef(&config.GraphOptions, nil), []string{"-storage-opt"}, usageFn("Set storage driver options"))
cmd.Var(opts.NewListOptsRef(&config.AuthZPlugins, nil), []string{"-authz-plugin"}, usageFn("List authorization plugins in order from first evaluator to last"))
cmd.Var(opts.NewListOptsRef(&config.ExecOptions, nil), []string{"-exec-opt"}, usageFn("Set exec driver options"))
cmd.StringVar(&config.Pidfile, []string{"p", "-pidfile"}, defaultPidFile, usageFn("Path to use for daemon PID file"))
cmd.StringVar(&config.Root, []string{"g", "-graph"}, defaultGraph, usageFn("Root of the Docker runtime"))
Expand Down
5 changes: 3 additions & 2 deletions docker/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,9 @@ func (cli *DaemonCli) CmdDaemon(args ...string) error {
}

serverConfig := &apiserver.Config{
Logging: true,
Version: dockerversion.Version,
AuthZPluginNames: cli.Config.AuthZPlugins,
Logging: true,
Version: dockerversion.Version,
}
serverConfig = setPlatformServerConfig(serverConfig, cli.Config)

Expand Down
252 changes: 252 additions & 0 deletions docs/extend/authorization.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
<!--[metadata]>
Copy link
Contributor

Choose a reason for hiding this comment

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

@liron-l thank you for the contribution. As @thaJeztah points out, there are several redundancies in this information. Also, structurally, I think there are opportunities to help the reader out by tightening the language used. A couple of questions come to mind:

  • The text mentions "authentication methods" are passed to the plugin. This implies there is some set of possible methods a plugin can expect. If there are, might a developer want to know what these are?
  • It would be nice to have a diagram of the flow here to help the reader visualize.
  • Is there a sample plugin we can point them to in our code or elsewhere?

Below I've included the complete text the incorporates all my comments. You can reach at the gist indicated.

---> https://gist.github.com/moxiegirl/852dbab3b392c28e29b2

Create an authorization plugin

Docker’s out-of-the-box authorization model is all or nothing. Any user with
permission to access to the Docker daemon can run any Docker client command. The
same is true for callers using Docker's remote API to contact the daemon. If you
require greater access control, you can create authorization plugins and add
them to your Docker daemon configuration. Using an authorization plugin, a
Docker administrator can configure granular access policies for managing access
to Docker daemon.

Anyone with the appropriate skills can develop an authorization plugin. These
skills, at their most basic, are knowledge of Docker, understanding of REST, and
sound programming knowledge. This document describes the architecture, state,
and methods information available to an authorization plugin developer.

Basic principles

Docker's plugin
infrastructure
enables
extending Docker by dynamically loading, removing and communicating with
third-party components using a generic API. The access authorization subsystem
was built using this mechanism.

Using this subsystem, you don't need to rebuild the Docker daemon to add an
authorization plugin. You can add a plugin to a installed Docker daemon. You do
need to restart the Docker daemon to add a new plugin.

An authorization plugin approves or denies requests to the Docker daemon based
on both the current authentication context and the command context. The
authentication context contains all user details and the authentication method.
The command context contains all the relevant request data.

Authorization plugins must follow the rules described in Docker Plugin
API
. Each plugin must reside
within directories described under the plugin
discovery

section.

Basic architecture

You are responsible for registering your plugin as part of the Docker daemon
startup. You can install multiple plugins and chain them together. This chain
can be ordered. Each request to the daemon passes in order through the chain.
Only when all the plugins grant access to the resource, is the access granted.

When an HTTP request is made to the Docker daemon through the CLI or via the
remote API, the authentication subsystem passes the request to the installed
authentication plugin(s). The request contains the user (caller) and command
context. The plugin is responsible for deciding whether to allow or deny the
request.

Each request sent to the plugin includes the authenticated user, the HTTP
headers, and the request/response body. Only the user name and the
authentication method used are passed to the plugin. Most importantly, no user
credentials or tokens are passed. Finally, not all request/response bodies
are sent to the authorization plugin. Only those request/response bodies where
the Content-Type is either text/* or application/json are sent.

For commands that can potentially the hijack the HTTP connection (HTTP Upgrade), such as exec, the authorization plugin are only called for the
initial HTTP requests. Once the plugin approves the command, authorization is
not applied to the rest of the flow. Specifically, the streaming data is not
passed to the authorization plugins. For commands that return chunked HTTP
response, such as logs and events, only the HTTP request are sent to the
authorization plugins as well.

During request/response processing, some authorization plugins flows might
need to do additional queries to the Docker daemon. To complete such flows,
plugins can call the daemon API similar to a regular user. To enable these
additional queries, the plugin must provide the means for an administrator to
configure proper authentication and security policies.

Docker client flows

To enable and configure the authorization plugin, the plugin developer must support the Docker client interactions detailed in this section.

Setting up Docker daemon

Enable the authorization plugin with a dedicated command line flag in the
--authz-plugins=PLUGIN_ID format. The flag supplies a PLUGIN_ID value.
This value can be the plugin’s socket or a path to a specification file.

$ docker daemon --authz-plugins=plugin1 --auth-plugins=plugin2,...

Docker's authorization subsystem supports multiple --authz-plugin parameters.

Calling authorized command (allow)

Your plugin must support calling the allow command to authorize a command. This call does not impact Docker's command line.

$ docker pull centos
...
f1b10cd84249: Pull complete
...

Calling unauthorized command (deny)

Your plugin must support calling the deny command to report on the outcome of a plugin interaction. This call returns messages to Docker's command line informing the user of the outcome of each call.

$ docker pull centos
…
Authorization failed. Pull command for user 'john_doe' is denied by authorization plugin 'ACME' with message ‘[ACME] User 'john_doe' is not allowed to perform the pull command’

Where multiple authorization plugins are installed, multiple messages are expected.

API schema and implementation

Sample code for a typical plugin can be found here [ADD LINK]. In addition to Docker's standard plugin registration method, each plugin should implement the following two methods:

  • /AuthzPlugin.AuthZReq This authorize request method is called before the Docker daemon processes the client request.
  • /AuthzPlugin.AuthZRes This authorize response method is called before the response is returned from Docker daemon to the client.

/AuthzPlugin.AuthZReq

Request:

{    
    "User":              "The user identification"
    "UserAuthNMethod":   "The authentication method used"
    "RequestMethod":     "The HTTP method"
    "RequestUri":        "The HTTP request URI"
    "RequestBody":       "Byte array containing the raw HTTP request body"
    "RequestHeader":     "Byte array containing the raw HTTP request header as a map[string][]string "
    "RequestStatusCode": "Request status code"
}

Response:

{    
    "Allow" : "Determined whether the user is allowed or not"
    "Msg":    "The authorization message"
}

/AuthzPlugin.AuthZRes

Request:

{
    "User":              "The user identification"
    "UserAuthNMethod":   "The authentication method used"
    "RequestMethod":     "The HTTP method"
    "RequestUri":        "The HTTP request URI"
    "RequestBody":       "Byte array containing the raw HTTP request body"
    "RequestHeader":     "Byte array containing the raw HTTP request header as a map[string][]string"
    "RequestStatusCode": "Request status code"
    "ResponseBody":      "Byte array containing the raw HTTP response body"
    "ResponseHeader":    "Byte array containing the raw HTTP response header as a map[string][]string"
    "ResponseStatusCode":"Response status code"
}

Response:

{
   "Allow" :               "Determined whether the user is allowed or not"
   "Msg":                  "The authorization message"
   "ModifiedBody":         "Byte array containing a modified body of the raw HTTP body (or nil if no changes required)"
   "ModifiedHeader":       "Byte array containing a modified header of the HTTP response (or nil if no changes required)"
   "ModifiedStatusCode":   "int containing the modified version of the status code (or 0 if not change is required)"
}

The modified response enables the authorization plugin to manipulate the content
of the HTTP response. In case of more than one plugin, each subsequent plugin
receives a response (optionally) modified by a previous plugin.

Request authorization

Each plugin must support two request authorization messages formats, one from the daemon to the plugin and then from the plugin to the daemon. The tables below detail the content expected in each message.

Daemon -> Plugin

Name Type Description
User string The user identification
Authentication method string The authentication method used
Request method enum The HTTP method (GET/DELETE/POST)
Request URI string The HTTP request URI including API version (e.g., v.1.17/containers/json)
Request headers map[string]string Request headers as key value pairs (without the authorization header)
Request body []byte Raw request body

Plugin -> Daemon

Name Type Description
Allow bool Boolean value indicating whether the request is allowed or denied
Message string Authorization message (will be returned to the client in case the access is denied)

Response authorization

The plugin must support two authorization messages formats, one from the daemon to the plugin and then from the plugin to the daemon. The tables below detail the content expected in each message.

Daemon -> Plugin

Name Type Description
User string The user identification
Authentication method string The authentication method used
Request method string The HTTP method (GET/DELETE/POST)
Request URI string The http request URI including API version (e.g., v.1.17/containers/json)
Request headers map[string]string Request headers as key value pairs (without the authorization header)
Request body []byte Raw request body
Response status code int Status code from the docker daemon
Response headers map[string]string Response headers as key value pairs
Response body []byte Raw docker daemon response body

Plugin -> Daemon

Name Type Description
Allow bool Boolean value indicating whether the response is allowed or denied
Message string Authorization message (will be returned to the client in case the access is denied)

+++
title = "Access authorization plugin"
description = "How to create authorization plugins to manage access control to your Docker daemon."
keywords = ["security, authorization, authentication, docker, documentation, plugin, extend"]
[menu.main]
parent = "mn_extend"
weight = -1
+++
<![end-metadata]-->


# Create an authorization plugin

Docker’s out-of-the-box authorization model is all or nothing. Any user with
permission to access the Docker daemon can run any Docker client command. The
same is true for callers using Docker's remote API to contact the daemon. If you
require greater access control, you can create authorization plugins and add
them to your Docker daemon configuration. Using an authorization plugin, a
Docker administrator can configure granular access policies for managing access
to Docker daemon.

Anyone with the appropriate skills can develop an authorization plugin. These
skills, at their most basic, are knowledge of Docker, understanding of REST, and
sound programming knowledge. This document describes the architecture, state,
and methods information available to an authorization plugin developer.

## Basic principles

Docker's [plugin infrastructure](plugin_api.md) enables
extending Docker by loading, removing and communicating with
third-party components using a generic API. The access authorization subsystem
was built using this mechanism.

Using this subsystem, you don't need to rebuild the Docker daemon to add an
authorization plugin. You can add a plugin to an installed Docker daemon. You do
need to restart the Docker daemon to add a new plugin.

An authorization plugin approves or denies requests to the Docker daemon based
on both the current authentication context and the command context. The
authentication context contains all user details and the authentication method.
The command context contains all the relevant request data.

Authorization plugins must follow the rules described in [Docker Plugin API](plugin_api.md).
Each plugin must reside within directories described under the
[Plugin discovery](plugin_api.md#plugin-discovery) section.

## Basic architecture

You are responsible for registering your plugin as part of the Docker daemon
startup. You can install multiple plugins and chain them together. This chain
can be ordered. Each request to the daemon passes in order through the chain.
Only when all the plugins grant access to the resource, is the access granted.

When an HTTP request is made to the Docker daemon through the CLI or via the
remote API, the authentication subsystem passes the request to the installed
authentication plugin(s). The request contains the user (caller) and command
context. The plugin is responsible for deciding whether to allow or deny the
request.

The sequence diagrams below depict an allow and deny authorization flow:

![Authorization Allow flow](images/authz_allow.png)

![Authorization Deny flow](images/authz_deny.png)

Each request sent to the plugin includes the authenticated user, the HTTP
headers, and the request/response body. Only the user name and the
authentication method used are passed to the plugin. Most importantly, no user
credentials or tokens are passed. Finally, not all request/response bodies
are sent to the authorization plugin. Only those request/response bodies where
the `Content-Type` is either `text/*` or `application/json` are sent.

For commands that can potentially hijack the HTTP connection (`HTTP
Upgrade`), such as `exec`, the authorization plugin is only called for the
initial HTTP requests. Once the plugin approves the command, authorization is
not applied to the rest of the flow. Specifically, the streaming data is not
passed to the authorization plugins. For commands that return chunked HTTP
response, such as `logs` and `events`, only the HTTP request is sent to the
authorization plugins.

During request/response processing, some authorization flows might
need to do additional queries to the Docker daemon. To complete such flows,
plugins can call the daemon API similar to a regular user. To enable these
additional queries, the plugin must provide the means for an administrator to
configure proper authentication and security policies.

## Docker client flows

To enable and configure the authorization plugin, the plugin developer must
support the Docker client interactions detailed in this section.

### Setting up Docker daemon

Enable the authorization plugin with a dedicated command line flag in the
`--authz-plugin=PLUGIN_ID` format. The flag supplies a `PLUGIN_ID` value.
This value can be the plugin’s socket or a path to a specification file.

```bash
$ docker daemon --authz-plugin=plugin1 --authz-plugin=plugin2,...
```

Docker's authorization subsystem supports multiple `--authz-plugin` parameters.
Copy link
Member

Choose a reason for hiding this comment

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

Should be --authz-plugins (plural)


### Calling authorized command (allow)

Your plugin must support calling the `allow` command to authorize a command.
This call does not impact Docker's command line.

```bash
$ docker pull centos
...
f1b10cd84249: Pull complete
...
```

### Calling unauthorized command (deny)

Your plugin must support calling the `deny` command to report on the outcome of
a plugin interaction. This call returns messages to Docker's command line informing
the user of the outcome of each call.

```bash
$ docker pull centos
Authorization failed. Pull command for user 'john_doe' is
denied by authorization plugin 'ACME' with message
‘[ACME] User 'john_doe' is not allowed to perform the pull
command’
```

Where multiple authorization plugins are installed, multiple messages are expected.


## API schema and implementation

In addition to Docker's standard plugin registration method, each plugin
should implement the following two methods:

* `/AuthzPlugin.AuthZReq` This authorize request method is called before the Docker daemon processes the client request.

* `/AuthzPlugin.AuthZRes` This authorize response method is called before the response is returned from Docker daemon to the client.

#### /AuthzPlugin.AuthZReq

**Request**:

```json
{
"User": "The user identification"
"UserAuthNMethod": "The authentication method used"
"RequestMethod": "The HTTP method"
"RequestUri": "The HTTP request URI"
"RequestBody": "Byte array containing the raw HTTP request body"
"RequestHeader": "Byte array containing the raw HTTP request header as a map[string][]string "
"RequestStatusCode": "Request status code"
}
```

**Response**:

```json
{
"Allow" : "Determined whether the user is allowed or not"
"Msg": "The authorization message"
}
```

#### /AuthzPlugin.AuthZRes

**Request**:

```json
{
"User": "The user identification"
"UserAuthNMethod": "The authentication method used"
"RequestMethod": "The HTTP method"
"RequestUri": "The HTTP request URI"
"RequestBody": "Byte array containing the raw HTTP request body"
"RequestHeader": "Byte array containing the raw HTTP request header as a map[string][]string"
"RequestStatusCode": "Request status code"
"ResponseBody": "Byte array containing the raw HTTP response body"
"ResponseHeader": "Byte array containing the raw HTTP response header as a map[string][]string"
"ResponseStatusCode":"Response status code"
}
```

**Response**:

```json
{
"Allow" : "Determined whether the user is allowed or not"
"Msg": "The authorization message"
"ModifiedBody": "Byte array containing a modified body of the raw HTTP body (or nil if no changes required)"
"ModifiedHeader": "Byte array containing a modified header of the HTTP response (or nil if no changes required)"
"ModifiedStatusCode": "int containing the modified version of the status code (or 0 if not change is required)"
}
```

The modified response enables the authorization plugin to manipulate the content
of the HTTP response. In case of more than one plugin, each subsequent plugin
receives a response (optionally) modified by a previous plugin.

### Request authorization

Each plugin must support two request authorization messages formats, one from the daemon to the plugin and then from the plugin to the daemon. The tables below detail the content expected in each message.

#### Daemon -> Plugin

Name | Type | Description
-----------------------|-------------------|-------------------------------------------------------
User | string | The user identification
Authentication method | string | The authentication method used
Request method | enum | The HTTP method (GET/DELETE/POST)
Request URI | string | The HTTP request URI including API version (e.g., v.1.17/containers/json)
Request headers | map[string]string | Request headers as key value pairs (without the authorization header)
Request body | []byte | Raw request body


#### Plugin -> Daemon

Name | Type | Description
--------|--------|----------------------------------------------------------------------------------
Allow | bool | Boolean value indicating whether the request is allowed or denied
Message | string | Authorization message (will be returned to the client in case the access is denied)

### Response authorization

The plugin must support two authorization messages formats, one from the daemon to the plugin and then from the plugin to the daemon. The tables below detail the content expected in each message.

#### Daemon -> Plugin


Name | Type | Description
----------------------- |------------------ |----------------------------------------------------
User | string | The user identification
Authentication method | string | The authentication method used
Request method | string | The HTTP method (GET/DELETE/POST)
Request URI | string | The HTTP request URI including API version (e.g., v.1.17/containers/json)
Request headers | map[string]string | Request headers as key value pairs (without the authorization header)
Request body | []byte | Raw request body
Response status code | int | Status code from the docker daemon
Response headers | map[string]string | Response headers as key value pairs
Response body | []byte | Raw docker daemon response body


#### Plugin -> Daemon

Name | Type | Description
--------|--------|----------------------------------------------------------------------------------
Allow | bool | Boolean value indicating whether the response is allowed or denied
Message | string | Authorization message (will be returned to the client in case the access is denied)
Binary file added docs/extend/images/authz_additional_info.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/extend/images/authz_allow.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/extend/images/authz_chunked.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/extend/images/authz_connection_hijack.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/extend/images/authz_deny.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading