CVE-2022-39388 (Go, published 2022-11-10T20:15Z)
Description: value: Istio is an open platform to connect, manage, and secure microservices. In versions on the 1.15.x branch prior to 1.15.3, a user can impersonate any workload identity within the service mesh if they have localhost access to the Istiod control plane. Version 1.15.3 contains a patch for this issue. There are no known workarounds.
Severity: nan (CVSS v3 base score: 3.5)
Weakness: CWE-863 \u2014 Incorrect Authorization
The product performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.
Repository: https://github.com/istio/istio
Files changed:
go.mod
go.sum
licenses/github.com/alecholmes/xfccparser/LICENSE
licenses/github.com/alecthomas/participle/COPYING
pilot/pkg/bootstrap/server.go
pilot/pkg/features/pilot.go
pilot/pkg/xds/auth.go
pkg/security/security.go
security/pkg/nodeagent/caclient/providers/citadel/client_test.go
security/pkg/nodeagent/test/mock/caserver.go
security/pkg/server/ca/authenticate/cert_authenticator.go
security/pkg/server/ca/authenticate/xfcc_authenticator.go
security/pkg/server/ca/authenticate/xfcc_authenticator_test.go
security/pkg/server/ca/server.go
security/pkg/server/ca/server_test.go
Commit message: add xfcc authenticator (#39405)

* add xfcc authenticator

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* comments

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* go mod

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* lint

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* add license

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* fix

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* fix folder

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* add copying file

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* remove COPYING

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* address review comments

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* address comments

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* add cidr authenticator

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* lint

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* minor changes

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* add more comments

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* update based on review comments

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* fix test

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* address comments

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* address comments

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* review comments

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* add authentication manager

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* add test

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* fix test

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* fix test

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* address comments

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

* address comments

Signed-off-by: Rama Chavali <rama.rao@salesforce.com>

Vulnerable code:
	"strings"
	"Authenticate plain text requests - used if Istiod is behind a gateway handling TLS").Get()
	authFailMsgs := []string{}
	for _, authn := range s.Authenticators {
		u, err := authn.Authenticate(ctx)
		// If one authenticator passes, return
		if u != nil && u.Identities != nil && err == nil {
			return u.Identities, nil
		}
		authFailMsgs = append(authFailMsgs, fmt.Sprintf("Authenticator %s: %v", authn.AuthenticatorType(), err))
	}
	log.Errorf("Failed to authenticate client from %s: %s", peerInfo.Addr.String(), strings.Join(authFailMsgs, "; "))
	ca2 "istio.io/istio/security/pkg/server/ca"
		caller := ca2.Authenticate(ctx, []security.Authenticator{ca.Authenticator})
	"istio.io/istio/security/pkg/server/ca"
		caller := ca.Authenticate(ctx, s.Authenticators)
	"golang.org/x/net/context"
	"fmt"
	"google.golang.org/grpc/peer"
func getConnectionAddress(ctx context.Context) string {
	peerInfo, ok := peer.FromContext(ctx)
	peerAddr := "unknown"
	if ok {
		peerAddr = peerInfo.Addr.String()
	}
	return peerAddr
}

	caller := Authenticate(ctx, s.Authenticators)

// authenticate goes through a list of authenticators (provided client cert, k8s jwt, and ID token)
// and authenticates if one of them is valid.
func Authenticate(ctx context.Context, auth []security.Authenticator) *security.Caller {
	// TODO: apply different authenticators in specific order / according to configuration.
	var errMsg string
	for id, authn := range auth {
		u, err := authn.Authenticate(ctx)
		if err != nil {
			errMsg += fmt.Sprintf("Authenticator %s at index %d got error: %v. ", authn.AuthenticatorType(), id, err)
		}
		if u != nil && err == nil {
			serverCaLog.Debugf("Authentication successful through auth source %v", u.AuthSource)
			return u
		}
	}
	serverCaLog.Warnf("Authentication failed for %v: %s", getConnectionAddress(ctx), errMsg)
	return nil
}
			authenticators: []security.Authenticator{&mockAuthenticator{}},
			authenticators: []security.Authenticator{&mockAuthenticator{}},
			authenticators: []security.Authenticator{&mockAuthenticator{}},
			authenticators: []security.Authenticator{&mockAuthenticator{}},
			authenticators: []security.Authenticator{&mockAuthenticator{}},

Fixed code:
	github.com/alecholmes/xfccparser v0.1.0
	github.com/alecthomas/participle v0.4.1 // indirect
github.com/alecholmes/xfccparser v0.1.0 h1:/PBnzDBxfHJ66AinLNglzZH4oWLrc1/QTKlSoNNnei8=
github.com/alecholmes/xfccparser v0.1.0/go.mod h1:c1S35dudNR5aZ4Vf9zKCrEwC8iqwF4TcDAbU+RXQ5yY=
github.com/alecthomas/go-thrift v0.0.0-20170109061633-7914173639b2/go.mod h1:CxCgO+NdpMdi9SsTlGbc0W+/UNxO3I0AabOEJZ3w61w=
github.com/alecthomas/kong v0.2.1/go.mod h1:+inYUSluD+p4L8KdviBSgzcqEjUQOfC5fQDRFuc36lI=
github.com/alecthomas/participle v0.4.1 h1:P2PJWzwrSpuCWXKnzqvw0b0phSfH1kJo4p2HvLynVsI=
github.com/alecthomas/participle v0.4.1/go.mod h1:T8u4bQOSMwrkTWOSyt8/jSFPEnRtd0FKFMjVfYBlqPs=
github.com/alecthomas/repr v0.0.0-20181024024818-d37bc2a10ba1/go.mod h1:xTS7Pm1pD1mvyM075QCDSRqH6qRLXylzS24ZTpRiSzQ=
MIT License

Copyright (c) 2020 Alec Holmes

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Copyright (C) 2017 Alec Thomas

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
	if len(features.TrustedGatewayCIDR) > 0 {
		authenticators = append(authenticators, &authenticate.XfccAuthenticator{})
	}
	// TODO: Move this to proper API.
	trustedGatewayCIDR = env.RegisterStringVar(
		"TRUSTED_GATEWAY_CIDR",
		"",
		"If set, any connections from gateway to Istiod with this CIDR range are treated as trusted for using authenication mechanisms like XFCC."+
			" This can only be used when the network where Istiod and the authenticating gateways are running in a trusted/secure network",
	)

	TrustedGatewayCIDR = func() []string {
		return strings.Split(trustedGatewayCIDR.Get(), ",")
	}()

	"istio.io/istio/pkg/security"
	"Authenticate plain text requests - used if Istiod is running on a secure/trusted network").Get()
	am := security.AuthenticationManager{
		Authenticators: s.Authenticators,
	}
	if u := am.Authenticate(ctx); u != nil {
		return u.Identities, nil
	}
	log.Errorf("Failed to authenticate client from %s: %s", peerInfo.Addr.String(), am.FailedMessages())
	"google.golang.org/grpc/peer"
var securityLog = istiolog.RegisterScope("security", "security debugging", 0)

// Authenticator determines the caller identity based on request context.
// AuthenticationManager orchestrates all authenticators to perform authentication.
type AuthenticationManager struct {
	Authenticators []Authenticator
	// authFailMsgs contains list of messages that authenticator wants to record - mainly used for logging.
	authFailMsgs []string
}

// Authenticate loops through all the configured Authenticators and returns if one of the authenticator succeeds.
func (am *AuthenticationManager) Authenticate(ctx context.Context) *Caller {
	for _, authn := range am.Authenticators {
		u, err := authn.Authenticate(ctx)
		if u != nil && len(u.Identities) > 0 && err == nil {
			securityLog.Debugf("Authentication successful through auth source %v", u.AuthSource)
			return u
		}
		am.authFailMsgs = append(am.authFailMsgs, fmt.Sprintf("Authenticator %s: %v", authn.AuthenticatorType(), err))
	}
	return nil
}

func GetConnectionAddress(ctx context.Context) string {
	peerInfo, ok := peer.FromContext(ctx)
	peerAddr := "unknown"
	if ok {
		peerAddr = peerInfo.Addr.String()
	}
	return peerAddr
}

func (am *AuthenticationManager) FailedMessages() string {
	return strings.Join(am.authFailMsgs, "; ")
}

		am := security.AuthenticationManager{Authenticators: []security.Authenticator{ca.Authenticator}}
		caller := am.Authenticate(ctx)
		am := security.AuthenticationManager{Authenticators: s.Authenticators}
		caller := am.Authenticate(ctx)
			caServerLog.Errorf("Failed to authenticate client from %s: %s", security.GetConnectionAddress(ctx), am.FailedMessages())
	"context"
// Copyright Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package authenticate

import (
	"context"
	"fmt"
	"net"
	"net/http"
	"strings"

	"github.com/alecholmes/xfccparser"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/peer"

	"istio.io/istio/pilot/pkg/features"
	"istio.io/istio/pkg/security"
)

const (
	XfccAuthenticatorType = "XfccAuthenticator"
)

// XfccAuthenticator extracts identities from Xfcc header.
type XfccAuthenticator struct{}

var _ security.Authenticator = &XfccAuthenticator{}

func (xff XfccAuthenticator) AuthenticatorType() string {
	return XfccAuthenticatorType
}

// Authenticate extracts identities from Xfcc Header.
func (xff XfccAuthenticator) Authenticate(ctx context.Context) (*security.Caller, error) {
	peerInfo, _ := peer.FromContext(ctx)
	// First check if client is trusted client so that we can "trust" the Xfcc Header.
	if !isTrustedAddress(peerInfo.Addr.String(), features.TrustedGatewayCIDR) {
		return nil, fmt.Errorf("caller from %s is not in the trusted network. XfccAuthenticator can not be used", peerInfo.Addr.String())
	}
	meta, ok := metadata.FromIncomingContext(ctx)

	if !ok || len(meta.Get(xfccparser.ForwardedClientCertHeader)) == 0 {
		return nil, nil
	}
	xfccHeader := meta.Get(xfccparser.ForwardedClientCertHeader)[0]
	return buildSecurityCaller(xfccHeader)
}

// AuthenticateRequest validates Xfcc Header.
func (xff XfccAuthenticator) AuthenticateRequest(req *http.Request) (*security.Caller, error) {
	xfccHeader := req.Header.Get(xfccparser.ForwardedClientCertHeader)
	if len(xfccHeader) == 0 {
		return nil, nil
	}
	return buildSecurityCaller(xfccHeader)
}

func buildSecurityCaller(xfccHeader string) (*security.Caller, error) {
	clientCerts, err := xfccparser.ParseXFCCHeader(xfccHeader)
	if err != nil {
		message := fmt.Sprintf("error in parsing xfcc header: %v", err)
		return nil, fmt.Errorf(message)
	}
	if len(clientCerts) == 0 {
		message := "xfcc header does not have atleast one client certs"
		return nil, fmt.Errorf(message)
	}
	ids := []string{}
	for _, cc := range clientCerts {
		ids = append(ids, cc.URI)
		ids = append(ids, cc.DNS...)
		if cc.Subject != nil {
			ids = append(ids, cc.Subject.CommonName)
		}
	}

	return &security.Caller{
		AuthSource: security.AuthSourceClientCertificate,
		Identities: ids,
	}, nil
}

func isTrustedAddress(addr string, trustedCidrs []string) bool {
	for _, cidr := range trustedCidrs {
		if isInRange(addr, cidr) {
			return true
		}
	}
	// Always trust local host addresses.
	return net.ParseIP(addr).IsLoopback()
}

func isInRange(addr, cidr string) bool {
	if strings.Contains(cidr, "/") {
		ip, ipnet, err := net.ParseCIDR(cidr)
		if err != nil {
			return false
		}
		if ip.To4() == nil && ip.To16() == nil {
			return false
		}
		return ipnet.Contains(net.ParseIP(addr))
	}
	return false
}
// Copyright Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package authenticate

import (
	"net"
	"reflect"
	"strings"
	"testing"

	"github.com/alecholmes/xfccparser"
	"golang.org/x/net/context"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/peer"

	"istio.io/istio/pkg/security"
)

func TestIsTrustedAddress(t *testing.T) {
	cases := []struct {
		name    string
		cidr    string
		peer    string
		trusted bool
	}{
		{
			name:    "localhost client",
			cidr:    "",
			peer:    "127.0.0.1",
			trusted: true,
		},
		{
			name:    "external client without trusted cidr",
			cidr:    "",
			peer:    "172.0.0.1",
			trusted: false,
		},
		{
			name:    "cidr in range",
			cidr:    "172.17.0.0/16,192.17.0.0/16",
			peer:    "172.17.0.2",
			trusted: true,
		},
		{
			name:    "cidr in range with both ipv6 and ipv4",
			cidr:    "172.17.0.0/16,2001:db8:1234:1a00::/56",
			peer:    "2001:0db8:1234:1aff:ffff:ffff:ffff:ffff",
			trusted: true,
		},
		{
			name:    "cidr outside range",
			cidr:    "172.17.0.0/16,172.17.0.0/16",
			peer:    "110.17.0.2",
			trusted: false,
		},
	}

	for _, tt := range cases {
		t.Run(tt.name, func(t *testing.T) {
			if result := isTrustedAddress(tt.peer, strings.Split(tt.cidr, ",")); result != tt.trusted {
				t.Errorf("Unexpected authentication result: want %v but got %v",
					tt.trusted, result)
			}
		})
	}
}

func TestXfccAuthenticator(t *testing.T) {
	cases := []struct {
		name               string
		xfccHeader         string
		caller             *security.Caller
		authenticateErrMsg string
	}{
		{
			name:       "No xfcc header",
			xfccHeader: "",
			caller:     nil,
		},
		{
			name:               "junk xfcc header",
			xfccHeader:         `junk xfcc header`,
			authenticateErrMsg: `error in parsing xfcc header: invalid header format: unexpected token "junk xfcc header"`,
		},
		{
			name: "Xfcc Header single hop",
			// nolint lll
			xfccHeader: `Hash=meshclient;Subject="";URI=spiffe://mesh.example.com/ns/otherns/sa/othersa`,
			caller: &security.Caller{
				AuthSource: security.AuthSourceClientCertificate,
				Identities: []string{
					"spiffe://mesh.example.com/ns/otherns/sa/othersa",
				},
			},
		},
		{
			name: "Xfcc Header multiple hops",
			// nolint lll
			xfccHeader: `Hash=hash;Cert="-----BEGIN%20CERTIFICATE-----%0cert%0A-----END%20CERTIFICATE-----%0A";Subject="CN=hello,OU=hello,O=Acme\, Inc.";URI=spiffe://mesh.example.com/ns/firstns/sa/firstsa;DNS=hello.west.example.com;DNS=hello.east.example.com,By=spiffe://mesh.example.com/ns/hellons/sa/hellosa;Hash=again;Subject="";URI=spiffe://mesh.example.com/ns/otherns/sa/othersa`,
			caller: &security.Caller{
				AuthSource: security.AuthSourceClientCertificate,
				Identities: []string{
					"spiffe://mesh.example.com/ns/firstns/sa/firstsa",
					"hello.west.example.com",
					"hello.east.example.com",
					"hello",
					"spiffe://mesh.example.com/ns/otherns/sa/othersa",
				},
			},
		},
	}

	auth := &XfccAuthenticator{}

	for _, tt := range cases {
		t.Run(tt.name, func(t *testing.T) {
			md := metadata.MD{}
			if len(tt.xfccHeader) > 0 {
				md.Append(xfccparser.ForwardedClientCertHeader, tt.xfccHeader)
			}
			ctx := peer.NewContext(context.Background(), &peer.Peer{Addr: &net.IPAddr{IP: net.ParseIP("127.0.0.1").To4()}})
			ctx = metadata.NewIncomingContext(ctx, md)
			result, err := auth.Authenticate(ctx)
			if len(tt.authenticateErrMsg) > 0 {
				if err == nil {
					t.Errorf("Succeeded. Error expected: %v", err)
				} else if err.Error() != tt.authenticateErrMsg {
					t.Errorf("Incorrect error message: want %s but got %s",
						tt.authenticateErrMsg, err.Error())
				}
			} else if err != nil {
				t.Fatalf("Unexpected Error: %v", err)
			}

			if !reflect.DeepEqual(tt.caller, result) {
				t.Errorf("Unexpected authentication result: want %v but got %v",
					tt.caller, result)
			}
		})
	}
}
	am := security.AuthenticationManager{Authenticators: s.Authenticators}
	caller := am.Authenticate(ctx)
			authenticators: []security.Authenticator{&mockAuthenticator{identities: []string{"test-identity"}}},
			authenticators: []security.Authenticator{&mockAuthenticator{identities: []string{"test-identity"}}},
			authenticators: []security.Authenticator{&mockAuthenticator{identities: []string{"test-identity"}}},
			authenticators: []security.Authenticator{&mockAuthenticator{identities: []string{"test-identity"}}},
			authenticators: []security.Authenticator{&mockAuthenticator{identities: []string{"test-identity"}}},