Просмотр исходного кода

Merge pull request #1570 from smallstep/herman/improve-scep-request-handling

Improve SCEP request handling
Herman Slatman 3 лет назад
Родитель
Сommit
d1dd1fa69c
2 измененных файлов с 158 добавлено и 18 удалено
  1. 82 12
      scep/api/api.go
  2. 76 6
      scep/api/api_test.go

+ 82 - 12
scep/api/api.go

@@ -151,11 +151,14 @@ func decodeRequest(r *http.Request) (request, error) {
 	defer r.Body.Close()
 
 	method := r.Method
-	query := r.URL.Query()
+	query, err := url.ParseQuery(r.URL.RawQuery)
+	if err != nil {
+		return request{}, fmt.Errorf("failed parsing URL query: %w", err)
+	}
 
-	var operation string
-	if _, ok := query["operation"]; ok {
-		operation = query.Get("operation")
+	operation := query.Get("operation")
+	if operation == "" {
+		return request{}, errors.New("no operation provided")
 	}
 
 	switch method {
@@ -167,14 +170,10 @@ func decodeRequest(r *http.Request) (request, error) {
 				Message:   []byte{},
 			}, nil
 		case opnPKIOperation:
-			var message string
-			if _, ok := query["message"]; ok {
-				message = query.Get("message")
-			}
-			// TODO: verify this; right type of encoding? Needs additional transformations?
-			decodedMessage, err := base64.StdEncoding.DecodeString(message)
+			message := query.Get("message")
+			decodedMessage, err := decodeMessage(message, r)
 			if err != nil {
-				return request{}, err
+				return request{}, fmt.Errorf("failed decoding message: %w", err)
 			}
 			return request{
 				Operation: operation,
@@ -186,7 +185,7 @@ func decodeRequest(r *http.Request) (request, error) {
 	case http.MethodPost:
 		body, err := io.ReadAll(io.LimitReader(r.Body, maxPayloadSize))
 		if err != nil {
-			return request{}, err
+			return request{}, fmt.Errorf("failed reading request body: %w", err)
 		}
 		return request{
 			Operation: operation,
@@ -197,6 +196,77 @@ func decodeRequest(r *http.Request) (request, error) {
 	}
 }
 
+func decodeMessage(message string, r *http.Request) ([]byte, error) {
+	if message == "" {
+		return nil, errors.New("message must not be empty")
+	}
+
+	// decode the message, which should be base64 standard encoded. Any characters that
+	// were escaped in the original query, were unescaped as part of url.ParseQuery, so
+	// that doesn't need to be performed here. Return early if successful.
+	decodedMessage, err := base64.StdEncoding.DecodeString(message)
+	if err == nil {
+		return decodedMessage, nil
+	}
+
+	// only interested in corrupt input errors below this. This type of error is the
+	// most likely to return, but better safe than sorry.
+	var cie base64.CorruptInputError
+	if !errors.As(err, &cie) {
+		return nil, fmt.Errorf("failed base64 decoding message: %w", err)
+	}
+
+	// the below code is a workaround for macOS when it sends a GET PKIOperation, which seems to result
+	// in a query with the '+' and '/' not being percent encoded; only the padding ('=') is encoded.
+	// When that is unescaped in the code before this, this results in invalid base64. The workaround
+	// is to obtain the original query, extract the message, apply transformation(s) to make it valid
+	// base64 and try decoding it again. If it succeeds, the happy path can be followed with the patched
+	// message. Otherwise we still return an error.
+	rawQuery, err := parseRawQuery(r.URL.RawQuery)
+	if err != nil {
+		return nil, fmt.Errorf("failed to parse raw query: %w", err)
+	}
+
+	rawMessage := rawQuery.Get("message")
+	if rawMessage == "" {
+		return nil, errors.New("no message in raw query")
+	}
+
+	rawMessage = strings.ReplaceAll(rawMessage, "%3D", "=") // apparently the padding arrives encoded; the others (+, /) not?
+	decodedMessage, err = base64.StdEncoding.DecodeString(rawMessage)
+	if err != nil {
+		return nil, fmt.Errorf("failed base64 decoding raw message: %w", err)
+	}
+
+	return decodedMessage, nil
+}
+
+// parseRawQuery parses a URL query into url.Values. It skips
+// unescaping keys and values. This code is based on url.ParseQuery.
+func parseRawQuery(query string) (url.Values, error) {
+	m := make(url.Values)
+	err := parseRawQueryWithoutUnescaping(m, query)
+	return m, err
+}
+
+// parseRawQueryWithoutUnescaping parses the raw query into url.Values, skipping
+// unescaping of the parts. This code is based on url.parseQuery.
+func parseRawQueryWithoutUnescaping(m url.Values, query string) (err error) {
+	for query != "" {
+		var key string
+		key, query, _ = strings.Cut(query, "&")
+		if strings.Contains(key, ";") {
+			return errors.New("invalid semicolon separator in query")
+		}
+		if key == "" {
+			continue
+		}
+		key, value, _ := strings.Cut(key, "=")
+		m[key] = append(m[key], value)
+	}
+	return err
+}
+
 // lookupProvisioner loads the provisioner associated with the request.
 // Responds 404 if the provisioner does not exist.
 func lookupProvisioner(next http.HandlerFunc) http.HandlerFunc {

+ 76 - 6
scep/api/api_test.go

@@ -3,15 +3,27 @@ package api
 
 import (
 	"bytes"
+	"encoding/base64"
 	"errors"
+	"fmt"
 	"net/http"
 	"net/http/httptest"
-	"reflect"
+	"net/url"
+	"strings"
 	"testing"
 	"testing/iotest"
+
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
 )
 
 func Test_decodeRequest(t *testing.T) {
+	randomB64 := "wx/1mQ49TpdLRfvVjQhXNSe8RB3hjZEarqYp5XVIxpSbvOhQSs8hP2TgucID1IputbA8JC6CbsUpcVae3+8hRNqs5pTsSHP2aNxsw8AHGSX9dZVymSclkUV8irk+ztfEfs7aLA=="
+	expectedRandom, err := base64.StdEncoding.DecodeString(randomB64)
+	require.NoError(t, err)
+	weirdMacOSCase := "wx/1mQ49TpdLRfvVjQhXNSe8RB3hjZEarqYp5XVIxpSbvOhQSs8hP2TgucID1IputbA8JC6CbsUpcVae3+8hRNqs5pTsSHP2aNxsw8AHGSX9dZVymSclkUV8irk+ztfEfs7aLA%3D%3D"
+	expectedWeirdMacOSCase, err := base64.StdEncoding.DecodeString(strings.ReplaceAll(weirdMacOSCase, "%3D", "="))
+	require.NoError(t, err)
 	type args struct {
 		r *http.Request
 	}
@@ -21,6 +33,22 @@ func Test_decodeRequest(t *testing.T) {
 		want    request
 		wantErr bool
 	}{
+		{
+			name: "fail/invalid-query",
+			args: args{
+				r: httptest.NewRequest(http.MethodGet, "http://scep:8080/?operation=bla;message=invalid-separator", http.NoBody),
+			},
+			want:    request{},
+			wantErr: true,
+		},
+		{
+			name: "fail/empty-operation",
+			args: args{
+				r: httptest.NewRequest(http.MethodGet, "http://scep:8080/?operation=", http.NoBody),
+			},
+			want:    request{},
+			wantErr: true,
+		},
 		{
 			name: "fail/unsupported-method",
 			args: args{
@@ -37,6 +65,14 @@ func Test_decodeRequest(t *testing.T) {
 			want:    request{},
 			wantErr: true,
 		},
+		{
+			name: "fail/get-PKIOperation-empty-message",
+			args: args{
+				r: httptest.NewRequest(http.MethodGet, "http://scep:8080/?operation=PKIOperation&message=", http.NoBody),
+			},
+			want:    request{},
+			wantErr: true,
+		},
 		{
 			name: "fail/get-PKIOperation",
 			args: args{
@@ -86,6 +122,39 @@ func Test_decodeRequest(t *testing.T) {
 			},
 			wantErr: false,
 		},
+		{
+			name: "ok/get-PKIOperation-escaped",
+			args: args{
+				r: httptest.NewRequest(http.MethodGet, fmt.Sprintf("http://scep:8080/?operation=PKIOperation&message=%s", url.QueryEscape(randomB64)), http.NoBody),
+			},
+			want: request{
+				Operation: "PKIOperation",
+				Message:   expectedRandom,
+			},
+			wantErr: false,
+		},
+		{
+			name: "ok/get-PKIOperation-not-escaped", // bit of a special case, but this is supported because of the macOS case now
+			args: args{
+				r: httptest.NewRequest(http.MethodGet, fmt.Sprintf("http://scep:8080/?operation=PKIOperation&message=%s", randomB64), http.NoBody),
+			},
+			want: request{
+				Operation: "PKIOperation",
+				Message:   expectedRandom,
+			},
+			wantErr: false,
+		},
+		{
+			name: "ok/get-PKIOperation-weird-macos-case", // a special case for macOS, which seems to result in the message not arriving fully percent-encoded
+			args: args{
+				r: httptest.NewRequest(http.MethodGet, fmt.Sprintf("http://scep:8080/?operation=PKIOperation&message=%s", weirdMacOSCase), http.NoBody),
+			},
+			want: request{
+				Operation: "PKIOperation",
+				Message:   expectedWeirdMacOSCase,
+			},
+			wantErr: false,
+		},
 		{
 			name: "ok/post-PKIOperation",
 			args: args{
@@ -101,13 +170,14 @@ func Test_decodeRequest(t *testing.T) {
 	for _, tt := range tests {
 		t.Run(tt.name, func(t *testing.T) {
 			got, err := decodeRequest(tt.args.r)
-			if (err != nil) != tt.wantErr {
-				t.Errorf("decodeRequest() error = %v, wantErr %v", err, tt.wantErr)
+			if tt.wantErr {
+				assert.Error(t, err)
+				assert.Equal(t, tt.want, got)
 				return
 			}
-			if !reflect.DeepEqual(got, tt.want) {
-				t.Errorf("decodeRequest() = %v, want %v", got, tt.want)
-			}
+
+			assert.NoError(t, err)
+			assert.Equal(t, tt.want, got)
 		})
 	}
 }