Don't dump request body to log when too large

Fixes an issue where a client can send a large body but specifiy
application/json as the content-type, and cause Docker to consume lots
of RAM while trying to buffer the body so it can be dumped to the debug
log.

Signed-off-by: Brian Goff <cpuguy83@gmail.com>
This commit is contained in:
Brian Goff 2016-01-13 15:28:27 -05:00
parent 0ee64127ae
commit 89af3835d4
1 changed files with 34 additions and 21 deletions

View File

@ -1,9 +1,9 @@
package server package server
import ( import (
"bytes" "bufio"
"encoding/json" "encoding/json"
"io/ioutil" "io"
"net/http" "net/http"
"runtime" "runtime"
"strings" "strings"
@ -14,6 +14,7 @@ import (
"github.com/docker/docker/dockerversion" "github.com/docker/docker/dockerversion"
"github.com/docker/docker/errors" "github.com/docker/docker/errors"
"github.com/docker/docker/pkg/authorization" "github.com/docker/docker/pkg/authorization"
"github.com/docker/docker/pkg/ioutils"
"github.com/docker/docker/pkg/version" "github.com/docker/docker/pkg/version"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -27,14 +28,29 @@ func debugRequestMiddleware(handler httputils.APIFunc) httputils.APIFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
logrus.Debugf("%s %s", r.Method, r.RequestURI) logrus.Debugf("%s %s", r.Method, r.RequestURI)
if r.Method == "POST" { if r.Method != "POST" {
if err := httputils.CheckForJSON(r); err == nil { return handler(ctx, w, r, vars)
var buf bytes.Buffer }
if _, err := buf.ReadFrom(r.Body); err == nil { if err := httputils.CheckForJSON(r); err != nil {
r.Body.Close() return handler(ctx, w, r, vars)
r.Body = ioutil.NopCloser(&buf) }
maxBodySize := 4096 // 4KB
if r.ContentLength > int64(maxBodySize) {
return handler(ctx, w, r, vars)
}
body := r.Body
bufReader := bufio.NewReaderSize(body, maxBodySize)
r.Body = ioutils.NewReadCloserWrapper(bufReader, func() error { return body.Close() })
b, err := bufReader.Peek(maxBodySize)
if err != io.EOF {
// either there was an error reading, or the buffer is full (in which case the request is too large)
return handler(ctx, w, r, vars)
}
var postForm map[string]interface{} var postForm map[string]interface{}
if err := json.Unmarshal(buf.Bytes(), &postForm); err == nil { if err := json.Unmarshal(b, &postForm); err == nil {
if _, exists := postForm["password"]; exists { if _, exists := postForm["password"]; exists {
postForm["password"] = "*****" postForm["password"] = "*****"
} }
@ -45,9 +61,6 @@ func debugRequestMiddleware(handler httputils.APIFunc) httputils.APIFunc {
logrus.Debugf("form data: %q", postForm) logrus.Debugf("form data: %q", postForm)
} }
} }
}
}
}
return handler(ctx, w, r, vars) return handler(ctx, w, r, vars)
} }