github.com/ttys3/engine@v17.12.1-ce-rc2+incompatible/pkg/authorization/authz.go (about)

     1  package authorization
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"fmt"
     7  	"io"
     8  	"net/http"
     9  	"strings"
    10  
    11  	"github.com/docker/docker/pkg/ioutils"
    12  	"github.com/sirupsen/logrus"
    13  )
    14  
    15  const maxBodySize = 1048576 // 1MB
    16  
    17  // NewCtx creates new authZ context, it is used to store authorization information related to a specific docker
    18  // REST http session
    19  // A context provides two method:
    20  // Authenticate Request:
    21  // Call authZ plugins with current REST request and AuthN response
    22  // Request contains full HTTP packet sent to the docker daemon
    23  // https://docs.docker.com/engine/reference/api/
    24  //
    25  // Authenticate Response:
    26  // Call authZ plugins with full info about current REST request, REST response and AuthN response
    27  // The response from this method may contains content that overrides the daemon response
    28  // This allows authZ plugins to filter privileged content
    29  //
    30  // If multiple authZ plugins are specified, the block/allow decision is based on ANDing all plugin results
    31  // For response manipulation, the response from each plugin is piped between plugins. Plugin execution order
    32  // is determined according to daemon parameters
    33  func NewCtx(authZPlugins []Plugin, user, userAuthNMethod, requestMethod, requestURI string) *Ctx {
    34  	return &Ctx{
    35  		plugins:         authZPlugins,
    36  		user:            user,
    37  		userAuthNMethod: userAuthNMethod,
    38  		requestMethod:   requestMethod,
    39  		requestURI:      requestURI,
    40  	}
    41  }
    42  
    43  // Ctx stores a single request-response interaction context
    44  type Ctx struct {
    45  	user            string
    46  	userAuthNMethod string
    47  	requestMethod   string
    48  	requestURI      string
    49  	plugins         []Plugin
    50  	// authReq stores the cached request object for the current transaction
    51  	authReq *Request
    52  }
    53  
    54  // AuthZRequest authorized the request to the docker daemon using authZ plugins
    55  func (ctx *Ctx) AuthZRequest(w http.ResponseWriter, r *http.Request) error {
    56  	var body []byte
    57  	if sendBody(ctx.requestURI, r.Header) && r.ContentLength > 0 && r.ContentLength < maxBodySize {
    58  		var err error
    59  		body, r.Body, err = drainBody(r.Body)
    60  		if err != nil {
    61  			return err
    62  		}
    63  	}
    64  
    65  	var h bytes.Buffer
    66  	if err := r.Header.Write(&h); err != nil {
    67  		return err
    68  	}
    69  
    70  	ctx.authReq = &Request{
    71  		User:            ctx.user,
    72  		UserAuthNMethod: ctx.userAuthNMethod,
    73  		RequestMethod:   ctx.requestMethod,
    74  		RequestURI:      ctx.requestURI,
    75  		RequestBody:     body,
    76  		RequestHeaders:  headers(r.Header),
    77  	}
    78  
    79  	if r.TLS != nil {
    80  		for _, c := range r.TLS.PeerCertificates {
    81  			pc := PeerCertificate(*c)
    82  			ctx.authReq.RequestPeerCertificates = append(ctx.authReq.RequestPeerCertificates, &pc)
    83  		}
    84  	}
    85  
    86  	for _, plugin := range ctx.plugins {
    87  		logrus.Debugf("AuthZ request using plugin %s", plugin.Name())
    88  
    89  		authRes, err := plugin.AuthZRequest(ctx.authReq)
    90  		if err != nil {
    91  			return fmt.Errorf("plugin %s failed with error: %s", plugin.Name(), err)
    92  		}
    93  
    94  		if !authRes.Allow {
    95  			return newAuthorizationError(plugin.Name(), authRes.Msg)
    96  		}
    97  	}
    98  
    99  	return nil
   100  }
   101  
   102  // AuthZResponse authorized and manipulates the response from docker daemon using authZ plugins
   103  func (ctx *Ctx) AuthZResponse(rm ResponseModifier, r *http.Request) error {
   104  	ctx.authReq.ResponseStatusCode = rm.StatusCode()
   105  	ctx.authReq.ResponseHeaders = headers(rm.Header())
   106  
   107  	if sendBody(ctx.requestURI, rm.Header()) {
   108  		ctx.authReq.ResponseBody = rm.RawBody()
   109  	}
   110  
   111  	for _, plugin := range ctx.plugins {
   112  		logrus.Debugf("AuthZ response using plugin %s", plugin.Name())
   113  
   114  		authRes, err := plugin.AuthZResponse(ctx.authReq)
   115  		if err != nil {
   116  			return fmt.Errorf("plugin %s failed with error: %s", plugin.Name(), err)
   117  		}
   118  
   119  		if !authRes.Allow {
   120  			return newAuthorizationError(plugin.Name(), authRes.Msg)
   121  		}
   122  	}
   123  
   124  	rm.FlushAll()
   125  
   126  	return nil
   127  }
   128  
   129  // drainBody dump the body (if its length is less than 1MB) without modifying the request state
   130  func drainBody(body io.ReadCloser) ([]byte, io.ReadCloser, error) {
   131  	bufReader := bufio.NewReaderSize(body, maxBodySize)
   132  	newBody := ioutils.NewReadCloserWrapper(bufReader, func() error { return body.Close() })
   133  
   134  	data, err := bufReader.Peek(maxBodySize)
   135  	// Body size exceeds max body size
   136  	if err == nil {
   137  		logrus.Warnf("Request body is larger than: '%d' skipping body", maxBodySize)
   138  		return nil, newBody, nil
   139  	}
   140  	// Body size is less than maximum size
   141  	if err == io.EOF {
   142  		return data, newBody, nil
   143  	}
   144  	// Unknown error
   145  	return nil, newBody, err
   146  }
   147  
   148  // sendBody returns true when request/response body should be sent to AuthZPlugin
   149  func sendBody(url string, header http.Header) bool {
   150  	// Skip body for auth endpoint
   151  	if strings.HasSuffix(url, "/auth") {
   152  		return false
   153  	}
   154  
   155  	// body is sent only for text or json messages
   156  	return header.Get("Content-Type") == "application/json"
   157  }
   158  
   159  // headers returns flatten version of the http headers excluding authorization
   160  func headers(header http.Header) map[string]string {
   161  	v := make(map[string]string)
   162  	for k, values := range header {
   163  		// Skip authorization headers
   164  		if strings.EqualFold(k, "Authorization") || strings.EqualFold(k, "X-Registry-Config") || strings.EqualFold(k, "X-Registry-Auth") {
   165  			continue
   166  		}
   167  		for _, val := range values {
   168  			v[k] = val
   169  		}
   170  	}
   171  	return v
   172  }
   173  
   174  // authorizationError represents an authorization deny error
   175  type authorizationError struct {
   176  	error
   177  }
   178  
   179  func (authorizationError) Forbidden() {}
   180  
   181  func newAuthorizationError(plugin, msg string) authorizationError {
   182  	return authorizationError{error: fmt.Errorf("authorization denied by plugin %s: %s", plugin, msg)}
   183  }