Skip to content

Commit

Permalink
Merge pull request #2200 from openziti/fix.2159.ha.api.session.certs
Browse files Browse the repository at this point in the history
fixes #2154 500 error on mfa enrollment in HA, fixes #2159 HA api session certs
  • Loading branch information
andrewpmartinez authored Jul 30, 2024
2 parents 28fb11b + 353cf93 commit 7886bc2
Show file tree
Hide file tree
Showing 13 changed files with 458 additions and 63 deletions.
90 changes: 90 additions & 0 deletions common/spiffehlp/spiffe.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
Copyright NetFoundry Inc.
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
https://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 spiffehlp

import (
"crypto/tls"
"crypto/x509"
"fmt"
"github.com/pkg/errors"
"net/url"
)

// GetSpiffeIdFromCertChain cycles through a slice of certificates that goes from leaf up CAs. Each certificate
// must contain 0 or 1 spiffe:// URI SAN. The first encountered SPIFFE id looking up the chain back to the root CA is returned.
// If no SPIFFE id is encountered, nil is returned. Errors are returned for parsing and processing errors only.
func GetSpiffeIdFromCertChain(certs []*x509.Certificate) (*url.URL, error) {
var spiffeId *url.URL
for _, cert := range certs {
var err error
spiffeId, err = GetSpiffeIdFromCert(cert)

if err != nil {
return nil, fmt.Errorf("failed to determine SPIFFE ID from x509 certificate chain: %w", err)
}

if spiffeId != nil {
return spiffeId, nil
}
}

return nil, errors.New("failed to determine SPIFFE ID, no spiffe:// URI SANs found in x509 certificate chain")
}

// GetSpiffeIdFromTlsCertChain will search a tls certificate chain for a trust domain encoded as a spiffe:// URI SAN.
// Each certificate must contain 0 or 1 spiffe:// URI SAN. The first SPIFFE id looking up the chain is returned. If
// no SPIFFE id is encountered, nil is returned. Errors are returned for parsing and processing errors only.
func GetSpiffeIdFromTlsCertChain(tlsCerts []*tls.Certificate) (*url.URL, error) {
for _, tlsCert := range tlsCerts {
for i, rawCert := range tlsCert.Certificate {
cert, err := x509.ParseCertificate(rawCert)

if err != nil {
return nil, fmt.Errorf("failed to parse TLS cert at index [%d]: %w", i, err)
}

spiffeId, err := GetSpiffeIdFromCert(cert)

if err != nil {
return nil, fmt.Errorf("failed to determine SPIFFE ID from TLS cert at index [%d]: %w", i, err)
}

if spiffeId != nil {
return spiffeId, nil
}
}
}

return nil, nil
}

// GetSpiffeIdFromCert will search a x509 certificate for a trust domain encoded as a spiffe:// URI SAN.
// Each certificate must contain 0 or 1 spiffe:// URI SAN. The first SPIFFE id looking up the chain is returned. If
// no SPIFFE id is encountered, nil is returned. Errors are returned for parsing and processing errors only.
func GetSpiffeIdFromCert(cert *x509.Certificate) (*url.URL, error) {
var spiffeId *url.URL
for _, uriSan := range cert.URIs {
if uriSan.Scheme == "spiffe" {
if spiffeId != nil {
return nil, fmt.Errorf("multiple URI SAN spiffe:// ids encountered, must only have one, encountered at least two: [%s] and [%s]", spiffeId.String(), uriSan.String())
}
spiffeId = uriSan
}
}

return spiffeId, nil
}
21 changes: 15 additions & 6 deletions controller/internal/routes/current_api_session_router.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"github.com/openziti/edge-api/rest_model"
"github.com/openziti/ziti/controller/env"
"github.com/openziti/ziti/controller/internal/permissions"
"github.com/openziti/ziti/controller/model"
"github.com/openziti/ziti/controller/response"
"net/http"
"time"
Expand Down Expand Up @@ -125,7 +126,15 @@ func (router *CurrentSessionRouter) ListCertificates(ae *env.AppEnv, rc *respons
func (router *CurrentSessionRouter) CreateCertificate(ae *env.AppEnv, rc *response.RequestContext, params clientCurrentApiSession.CreateCurrentAPISessionCertificateParams) {
responder := &ApiSessionCertificateCreateResponder{ae: ae, Responder: rc}
CreateWithResponder(rc, responder, CurrentApiSessionCertificateLinkFactory, func() (string, error) {
return ae.GetManagers().ApiSessionCertificate.CreateFromCSR(rc.ApiSession.Id, 12*time.Hour, []byte(*params.SessionCertificate.Csr), rc.NewChangeContext())
newApiSessionCert, err := ae.GetManagers().ApiSessionCertificate.CreateFromCSR(rc.Identity, rc.ApiSession, rc.IsJwtToken, 12*time.Hour, []byte(*params.SessionCertificate.Csr), rc.NewChangeContext())

if err != nil {
return "", err
}

responder.ApiSessionCertificate = newApiSessionCert

return newApiSessionCert.Id, nil
})
}

Expand Down Expand Up @@ -191,18 +200,18 @@ func (router *CurrentSessionRouter) ListServiceUpdates(ae *env.AppEnv, rc *respo

type ApiSessionCertificateCreateResponder struct {
response.Responder
ae *env.AppEnv
ApiSessionCertificate *model.ApiSessionCertificate
ae *env.AppEnv
}

func (nsr *ApiSessionCertificateCreateResponder) RespondWithCreatedId(id string, _ rest_model.Link) {
sessionCert, _ := nsr.ae.GetManagers().ApiSessionCertificate.Read(id)
certString := sessionCert.PEM
certString := nsr.ApiSessionCertificate.PEM

newSessionEnvelope := &rest_model.CreateCurrentAPISessionCertificateEnvelope{
Data: &rest_model.CurrentAPISessionCertificateCreateResponse{
CreateLocation: rest_model.CreateLocation{
Links: CurrentApiSessionCertificateLinkFactory.Links(sessionCert),
ID: sessionCert.Id,
Links: CurrentApiSessionCertificateLinkFactory.Links(nsr.ApiSessionCertificate),
ID: nsr.ApiSessionCertificate.Id,
},
Certificate: &certString,
Cas: string(nsr.ae.GetConfig().Edge.CaPems()),
Expand Down
10 changes: 6 additions & 4 deletions controller/internal/routes/current_identity_router.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,11 +144,13 @@ func (r *CurrentIdentityRouter) verifyMfa(ae *env.AppEnv, rc *response.RequestCo
return
}

err = ae.Managers.ApiSession.SetMfaPassed(rc.ApiSession, changeCtx)
if !rc.IsJwtToken {
err = ae.Managers.ApiSession.SetMfaPassed(rc.ApiSession, changeCtx)

if err != nil {
rc.RespondWithError(err)
return
if err != nil {
rc.RespondWithError(err)
return
}
}

rc.RespondWithEmptyOk()
Expand Down
40 changes: 32 additions & 8 deletions controller/model/api_session_certificate_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,15 @@ package model

import (
"crypto/x509"
"fmt"
"github.com/openziti/ziti/common/cert"
"github.com/openziti/ziti/common/eid"
"github.com/openziti/ziti/controller/apierror"
"github.com/openziti/ziti/controller/change"
"github.com/openziti/ziti/controller/db"
"github.com/openziti/ziti/controller/models"
"go.etcd.io/bbolt"
"net/url"
"time"
)

Expand All @@ -48,7 +51,7 @@ func (self *ApiSessionCertificateManager) Create(entity *ApiSessionCertificate,
return self.createEntity(entity, ctx.NewMutateContext())
}

func (self *ApiSessionCertificateManager) CreateFromCSR(apiSessionId string, lifespan time.Duration, csrPem []byte, ctx *change.Context) (string, error) {
func (self *ApiSessionCertificateManager) CreateFromCSR(identity *Identity, apiSession *ApiSession, isJwt bool, lifespan time.Duration, csrPem []byte, ctx *change.Context) (*ApiSessionCertificate, error) {
notBefore := time.Now()
notAfter := time.Now().Add(lifespan)

Expand All @@ -58,38 +61,59 @@ func (self *ApiSessionCertificateManager) CreateFromCSR(apiSessionId string, lif
apiErr := apierror.NewCouldNotProcessCsr()
apiErr.Cause = err
apiErr.AppendCause = true
return "", apiErr
return nil, apiErr
}

newId := eid.New()

trustDomain := self.env.GetConfig().SpiffeIdTrustDomain.Hostname()
spiffeId := &url.URL{
Scheme: "spiffe",
Host: trustDomain,
Path: fmt.Sprintf("identity/%s/apiSession/%s/apiSessionCertificate/%s", identity.Id, apiSession.Id, newId),
}

certRaw, err := self.env.GetApiClientCsrSigner().SignCsr(csr, &cert.SigningOpts{
NotAfter: &notAfter,
NotBefore: &notBefore,
URIs: []*url.URL{
spiffeId,
},
})

if err != nil {
apiErr := apierror.NewCouldNotProcessCsr()
apiErr.Cause = err
apiErr.AppendCause = true
return "", apiErr
return nil, apiErr
}

fp := self.env.GetFingerprintGenerator().FromRaw(certRaw)

certPem, _ := cert.RawToPem(certRaw)

cert, _ := x509.ParseCertificate(certRaw)
newCert, _ := x509.ParseCertificate(certRaw)

entity := &ApiSessionCertificate{
BaseEntity: models.BaseEntity{},
ApiSessionId: apiSessionId,
Subject: cert.Subject.String(),
BaseEntity: models.BaseEntity{
Id: newId,
},
ApiSessionId: apiSession.Id,
Subject: newCert.Subject.String(),
Fingerprint: fp,
ValidAfter: &notBefore,
ValidBefore: &notAfter,
PEM: string(certPem),
}

return self.Create(entity, ctx)
if isJwt {
// can't create if using bearer tokens, the API Session will not exist
return entity, nil
}

entity.Id, err = self.Create(entity, ctx)

return entity, err
}

func (self *ApiSessionCertificateManager) IsUpdated(_ string) bool {
Expand Down
6 changes: 6 additions & 0 deletions controller/model/authenticator_mod_ext_jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,11 @@ func (a *AuthModuleExtJwt) process(context AuthContext, isPrimary bool) (AuthRes

var verifyResults []*candidateResult

if len(candidates) == 0 {
logger.Error("encountered 0 candidate JWTs, verification cannot occur")
return nil, apierror.NewInvalidAuth()
}

for i, candidate := range candidates {
verifyResult := a.verifyCandidate(context, isPrimary, candidate)

Expand All @@ -378,6 +383,7 @@ func (a *AuthModuleExtJwt) process(context AuthContext, isPrimary bool) (AuthRes
if isPrimary {
authType = "primary"
}

logger.Errorf("encountered %d candidate JWTs and all failed to validate for %s authentication, see the following log messages", len(verifyResults), authType)
for i, result := range verifyResults {
result.LogResult(logger, i)
Expand Down
1 change: 1 addition & 0 deletions controller/response/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"github.com/openziti/ziti/common"
"github.com/openziti/ziti/controller/change"
"github.com/openziti/ziti/controller/model"

"net/http"
"time"
)
Expand Down
8 changes: 4 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ require (
github.com/kr/pty v1.1.8 // indirect
github.com/kyokomi/emoji/v2 v2.2.12 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/lufia/plan9stats v0.0.0-20240408141607-282e7b5d6b74 // indirect
github.com/lufia/plan9stats v0.0.0-20240513124658-fba389f38bae // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
Expand Down Expand Up @@ -182,11 +182,11 @@ require (
go.opentelemetry.io/otel/trace v1.28.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 // indirect
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 // indirect
golang.org/x/image v0.13.0 // indirect
golang.org/x/mod v0.18.0 // indirect
golang.org/x/mod v0.19.0 // indirect
golang.org/x/term v0.22.0 // indirect
golang.org/x/tools v0.22.0 // indirect
golang.org/x/tools v0.23.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
nhooyr.io/websocket v1.8.11 // indirect
Expand Down
16 changes: 8 additions & 8 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -458,8 +458,8 @@ github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/lucsky/cuid v1.2.1 h1:MtJrL2OFhvYufUIn48d35QGXyeTC8tn0upumW9WwTHg=
github.com/lucsky/cuid v1.2.1/go.mod h1:QaaJqckboimOmhRSJXSx/+IT+VTfxfPGSo/6mfgUfmE=
github.com/lufia/plan9stats v0.0.0-20240408141607-282e7b5d6b74 h1:1KuuSOy4ZNgW0KA2oYIngXVFhQcXxhLqCVK7cBcldkk=
github.com/lufia/plan9stats v0.0.0-20240408141607-282e7b5d6b74/go.mod h1:ilwx/Dta8jXAgpFYFvSWEMwxmbWXyiUHkd5FwyKhb5k=
github.com/lufia/plan9stats v0.0.0-20240513124658-fba389f38bae h1:dIZY4ULFcto4tAFlj1FYZl8ztUZ13bdq+PLY+NOfbyI=
github.com/lufia/plan9stats v0.0.0-20240513124658-fba389f38bae/go.mod h1:ilwx/Dta8jXAgpFYFvSWEMwxmbWXyiUHkd5FwyKhb5k=
github.com/lunixbochs/vtclean v1.0.0/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI=
github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60=
Expand Down Expand Up @@ -872,8 +872,8 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0
golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4=
golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM=
golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU=
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 h1:vr/HnozRka3pE4EsMEg1lgkXJkTFJCVUX+S/ZT6wYzM=
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc=
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 h1:2dVuKD2vS7b0QIHQbpyTISPd0LeHDbnYEryqj5Q1ug8=
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56/go.mod h1:M4RDyNAINzryxdtnbRXRL/OHtkFuWGRjvuhBJpk2IlY=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
Expand Down Expand Up @@ -906,8 +906,8 @@ golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.18.0 h1:5+9lSbEzPSdWkH32vYPBwEpX8KwDbM52Ud9xBUvNlb0=
golang.org/x/mod v0.18.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.19.0 h1:fEdghXQSo20giMthA7cd28ZC+jts4amQ3YMXiP5oMQ8=
golang.org/x/mod v0.19.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
Expand Down Expand Up @@ -1163,8 +1163,8 @@ golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0=
golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.22.0 h1:gqSGLZqv+AI9lIQzniJ0nZDRG5GBPsSi+DRNHWNz6yA=
golang.org/x/tools v0.22.0/go.mod h1:aCwcsjqvq7Yqt6TNyX7QMU2enbQ/Gt0bo6krSeEri+c=
golang.org/x/tools v0.23.0 h1:SGsXPZ+2l4JsgaCKkx+FQ9YZ5XEtA1GZYuoDjenLjvg=
golang.org/x/tools v0.23.0/go.mod h1:pnu6ufv6vQkll6szChhK3C3L/ruaIv5eBeztNG8wtsI=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
Expand Down
Loading

0 comments on commit 7886bc2

Please sign in to comment.