From 4effd55b479f325abc727b2cfc4011f7ffdced0a Mon Sep 17 00:00:00 2001 From: Wim Date: Sat, 6 Nov 2021 00:25:49 +0100 Subject: [PATCH 01/21] Implement http signatures support for the API Fixes #12338 --- go.mod | 1 + go.sum | 2 + services/auth/auth.go | 1 + services/auth/httpsign.go | 176 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 180 insertions(+) create mode 100644 services/auth/httpsign.go diff --git a/go.mod b/go.mod index ea7a3108f563..7a6b052bd464 100644 --- a/go.mod +++ b/go.mod @@ -40,6 +40,7 @@ require ( github.com/go-chi/chi/v5 v5.0.4 github.com/go-chi/cors v1.2.0 github.com/go-enry/go-enry/v2 v2.7.1 + github.com/go-fed/httpsig v1.1.0 github.com/go-git/go-billy/v5 v5.3.1 github.com/go-git/go-git/v5 v5.4.3-0.20210630082519-b4368b2a2ca4 github.com/go-ldap/ldap/v3 v3.3.0 diff --git a/go.sum b/go.sum index 71ca3f67e1f6..046e69ffbc69 100644 --- a/go.sum +++ b/go.sum @@ -329,6 +329,8 @@ github.com/go-enry/go-enry/v2 v2.7.1 h1:WCqtfyteIz61GYk9lRVy8HblvIv4cP9GIiwm/6tx github.com/go-enry/go-enry/v2 v2.7.1/go.mod h1:GVzIiAytiS5uT/QiuakK7TF1u4xDab87Y8V5EJRpsIQ= github.com/go-enry/go-oniguruma v1.2.1 h1:k8aAMuJfMrqm/56SG2lV9Cfti6tC4x8673aHCcBk+eo= github.com/go-enry/go-oniguruma v1.2.1/go.mod h1:bWDhYP+S6xZQgiRL7wlTScFYBe023B6ilRZbCAD5Hf4= +github.com/go-fed/httpsig v1.1.0 h1:9M+hb0jkEICD8/cAiNqEB66R87tTINszBRTjwjQzWcI= +github.com/go-fed/httpsig v1.1.0/go.mod h1:RCMrTZvN1bJYtofsG4rd5NaO5obxQ5xBkdiS7xsT7bM= github.com/go-git/gcfg v1.5.0 h1:Q5ViNfGF8zFgyJWPqYwA7qGFoMTEiBmdlkcfRmpIMa4= github.com/go-git/gcfg v1.5.0/go.mod h1:5m20vg6GwYabIxaOonVkTdrILxQMpEShl1xiMF4ua+E= github.com/go-git/go-billy/v5 v5.2.0/go.mod h1:pmpqyWchKfYfrkb/UVH4otLvyi/5gJlGI4Hb3ZqZ3W0= diff --git a/services/auth/auth.go b/services/auth/auth.go index 3eb7f027d2e7..63d2d3c4b3be 100644 --- a/services/auth/auth.go +++ b/services/auth/auth.go @@ -33,6 +33,7 @@ import ( var authMethods = []Method{ &OAuth2{}, &Basic{}, + &HTTPSign{}, &Session{}, } diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go new file mode 100644 index 000000000000..c193b1c0410f --- /dev/null +++ b/services/auth/httpsign.go @@ -0,0 +1,176 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package auth + +import ( + "bytes" + "encoding/base64" + "errors" + "fmt" + "net/http" + "strings" + + "code.gitea.io/gitea/models" + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/web/middleware" + "github.com/go-fed/httpsig" + "golang.org/x/crypto/ssh" +) + +// Ensure the struct implements the interface. +var ( + _ Method = &HTTPSign{} + _ Named = &HTTPSign{} +) + +// HTTPSign implements the Auth interface and authenticates requests (API requests +// only) by looking for http signature data in the "Signature" header. +// more information can be found on https://github.com/go-fed/httpsig +type HTTPSign struct { +} + +// Name represents the name of auth method +func (h *HTTPSign) Name() string { + return "httpsign" +} + +// Verify extracts and validates HTTPsign from the Signature header of the request and returns +// the corresponding user object on successful validation. +// Returns nil if header is empty or validation fails. +func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *models.User { + // HTTPSign authentication should only fire on API + if !middleware.IsAPIPath(req) { + return nil + } + + sigHead := req.Header.Get("Signature") + if len(sigHead) == 0 { + return nil + } + + if len(setting.SSH.TrustedUserCAKeys) == 0 { + return nil + } + + validpk, err := VerifyCert(req) + if err != nil { + log.Error("VerifyCert failed: %v", err) + } + + u, err := models.GetUserByID(validpk.OwnerID) + if err != nil { + log.Error("GetUserByID: %v", err) + return nil + } + + store.GetData()["IsApiToken"] = true + + log.Trace("HTTP Sign: Logged in user %-v", u) + + return u +} + +// VerifyCert verifies the validity of the ssh certificate and returns the publickey of the signer +// We verify that the certificate is signed with the correct CA +// We verify that the http request is signed with the private key (of the public key mentioned in the certificate) +func VerifyCert(r *http.Request) (*models.PublicKey, error) { + var validpk *models.PublicKey + + // Get our certificate from the header + bcert, err := base64.RawStdEncoding.DecodeString(r.Header.Get("x-ssh-certificate")) + if err != nil { + return validpk, err + } + + pk, err := ssh.ParsePublicKey(bcert) + if err != nil { + return validpk, err + } + + // Check if it's really a ssh certificate + if _, ok := pk.(*ssh.Certificate); !ok { + return validpk, fmt.Errorf("no certificate found") + } + + cert := pk.(*ssh.Certificate) + + for _, principal := range cert.ValidPrincipals { + validpk, err = models.SearchPublicKeyByContentExact(principal) + if err != nil { + log.Error("SearchPublicKeyByContentExact: %v", err) + return validpk, err + } + + if models.IsErrKeyNotExist(err) { + continue + } + + c := &ssh.CertChecker{ + IsUserAuthority: func(auth ssh.PublicKey) bool { + for _, k := range setting.SSH.TrustedUserCAKeysParsed { + if bytes.Equal(auth.Marshal(), k.Marshal()) { + return true + } + } + + return false + }, + } + + // check the CA of the cert + if !c.IsUserAuthority(cert.SignatureKey) { + return validpk, fmt.Errorf("CA check failed") + } + + // validate the cert for this principal + if err := c.CheckCert(principal, cert); err != nil { + return validpk, fmt.Errorf("no valid principal found") + } + + break + } + + verifier, err := httpsig.NewVerifier(r) + if err != nil { + return validpk, fmt.Errorf("httpsig.NewVerifier failed: %s", err) + } + + // now verify that we signed this request with the publickey of the cert + err = doVerify(verifier, []ssh.PublicKey{cert.Key}) + if err != nil { + return validpk, err + } + + return validpk, nil +} + +func doVerify(verifier httpsig.Verifier, publickeys []ssh.PublicKey) error { + verified := false + + for _, pubkey := range publickeys { + cryptoPubkey := pubkey.(ssh.CryptoPublicKey).CryptoPublicKey() + + var algo httpsig.Algorithm + + switch { + case strings.HasPrefix(pubkey.Type(), "ssh-ed25519"): + algo = httpsig.ED25519 + case strings.HasPrefix(pubkey.Type(), "ssh-rsa"): + algo = httpsig.RSA_SHA1 + } + + err := verifier.Verify(cryptoPubkey, algo) + if err == nil { + verified = true + } + } + + if verified { + return nil + } + + return errors.New("verification failed") +} From 465a7f4d6d7c394217b6bf37ca127b9776545547 Mon Sep 17 00:00:00 2001 From: Wim Date: Sat, 6 Nov 2021 18:35:25 +0100 Subject: [PATCH 02/21] Return nil on error --- services/auth/httpsign.go | 1 + 1 file changed, 1 insertion(+) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index c193b1c0410f..5d9034f2a2f8 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -58,6 +58,7 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt validpk, err := VerifyCert(req) if err != nil { log.Error("VerifyCert failed: %v", err) + return nil } u, err := models.GetUserByID(validpk.OwnerID) From c8c344e74cad108c86e95d0ab84e00b6972505dd Mon Sep 17 00:00:00 2001 From: Wim Date: Sat, 6 Nov 2021 20:16:02 +0100 Subject: [PATCH 03/21] Add Failed authentication attempt warning --- services/auth/httpsign.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index 5d9034f2a2f8..6785c50186ec 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -57,7 +57,8 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt validpk, err := VerifyCert(req) if err != nil { - log.Error("VerifyCert failed: %v", err) + log.Warn("Failed authentication attempt from %s", req.RemoteAddr) + log.Error("VerifyCert failed: %v", err) return nil } From 8612a727a49901d619d80069af1cdeb0b1ed0896 Mon Sep 17 00:00:00 2001 From: Wim Date: Thu, 2 Dec 2021 01:00:54 +0100 Subject: [PATCH 04/21] Fix upstream api changes to user_model --- services/auth/httpsign.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index 6785c50186ec..3bf9b71fd314 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -13,6 +13,7 @@ import ( "strings" "code.gitea.io/gitea/models" + user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/web/middleware" @@ -40,7 +41,7 @@ func (h *HTTPSign) Name() string { // Verify extracts and validates HTTPsign from the Signature header of the request and returns // the corresponding user object on successful validation. // Returns nil if header is empty or validation fails. -func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *models.User { +func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *user_model.User { // HTTPSign authentication should only fire on API if !middleware.IsAPIPath(req) { return nil @@ -62,7 +63,7 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt return nil } - u, err := models.GetUserByID(validpk.OwnerID) + u, err := user_model.GetUserByID(validpk.OwnerID) if err != nil { log.Error("GetUserByID: %v", err) return nil From b0005d5573dfd980a37b0ab78168cb8a831d64f4 Mon Sep 17 00:00:00 2001 From: Wim Date: Sun, 12 Dec 2021 01:35:57 +0100 Subject: [PATCH 05/21] Fix upstream api changes to asymkey_model --- services/auth/httpsign.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index 3bf9b71fd314..65dc978774e4 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -12,7 +12,7 @@ import ( "net/http" "strings" - "code.gitea.io/gitea/models" + asymkey_model "code.gitea.io/gitea/models/asymkey" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" @@ -79,8 +79,8 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt // VerifyCert verifies the validity of the ssh certificate and returns the publickey of the signer // We verify that the certificate is signed with the correct CA // We verify that the http request is signed with the private key (of the public key mentioned in the certificate) -func VerifyCert(r *http.Request) (*models.PublicKey, error) { - var validpk *models.PublicKey +func VerifyCert(r *http.Request) (*asymkey_model.PublicKey, error) { + var validpk *asymkey_model.PublicKey // Get our certificate from the header bcert, err := base64.RawStdEncoding.DecodeString(r.Header.Get("x-ssh-certificate")) @@ -101,13 +101,13 @@ func VerifyCert(r *http.Request) (*models.PublicKey, error) { cert := pk.(*ssh.Certificate) for _, principal := range cert.ValidPrincipals { - validpk, err = models.SearchPublicKeyByContentExact(principal) + validpk, err = asymkey_model.SearchPublicKeyByContentExact(principal) if err != nil { log.Error("SearchPublicKeyByContentExact: %v", err) return validpk, err } - if models.IsErrKeyNotExist(err) { + if asymkey_model.IsErrKeyNotExist(err) { continue } From c86617b477739c331327701d46d377f52ca50e9b Mon Sep 17 00:00:00 2001 From: Wim Date: Sun, 13 Feb 2022 13:50:10 +0100 Subject: [PATCH 06/21] Apply suggestions from code review Co-authored-by: Lunny Xiao --- services/auth/httpsign.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index 65dc978774e4..bcb1b52cf260 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -94,12 +94,11 @@ func VerifyCert(r *http.Request) (*asymkey_model.PublicKey, error) { } // Check if it's really a ssh certificate - if _, ok := pk.(*ssh.Certificate); !ok { + cert, ok := pk.(*ssh.Certificate) + if !ok { return validpk, fmt.Errorf("no certificate found") } - cert := pk.(*ssh.Certificate) - for _, principal := range cert.ValidPrincipals { validpk, err = asymkey_model.SearchPublicKeyByContentExact(principal) if err != nil { From 0cf37bb7838625b1b4ec42bf3ba389e64bc12178 Mon Sep 17 00:00:00 2001 From: Wim Date: Sun, 13 Feb 2022 13:56:17 +0100 Subject: [PATCH 07/21] Apply more suggestions from code review --- services/auth/httpsign.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index bcb1b52cf260..8a3d6812979d 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -17,6 +17,7 @@ import ( "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/web/middleware" + "github.com/go-fed/httpsig" "golang.org/x/crypto/ssh" ) @@ -102,14 +103,13 @@ func VerifyCert(r *http.Request) (*asymkey_model.PublicKey, error) { for _, principal := range cert.ValidPrincipals { validpk, err = asymkey_model.SearchPublicKeyByContentExact(principal) if err != nil { + if asymkey_model.IsErrKeyNotExist(err) { + continue + } log.Error("SearchPublicKeyByContentExact: %v", err) return validpk, err } - if asymkey_model.IsErrKeyNotExist(err) { - continue - } - c := &ssh.CertChecker{ IsUserAuthority: func(auth ssh.PublicKey) bool { for _, k := range setting.SSH.TrustedUserCAKeysParsed { @@ -167,6 +167,7 @@ func doVerify(verifier httpsig.Verifier, publickeys []ssh.PublicKey) error { err := verifier.Verify(cryptoPubkey, algo) if err == nil { verified = true + break } } From 98b5bd5efdaac5c7fa26c8ea9ccb95d6a25a60f0 Mon Sep 17 00:00:00 2001 From: Wim Date: Sun, 29 May 2022 20:10:59 +0200 Subject: [PATCH 08/21] Fix upstream main API changes --- routers/api/v1/api.go | 1 + services/auth/httpsign.go | 5 ++--- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 62c4a8934cab..e59dfd56ca92 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -592,6 +592,7 @@ func bind(obj interface{}) http.HandlerFunc { func buildAuthGroup() *auth.Group { group := auth.NewGroup( &auth.OAuth2{}, + &auth.HTTPSign{}, &auth.Basic{}, // FIXME: this should be removed once we don't allow basic auth in API ) if setting.Service.EnableReverseProxyAuth { diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index 8a3d6812979d..04af47afc69b 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -31,8 +31,7 @@ var ( // HTTPSign implements the Auth interface and authenticates requests (API requests // only) by looking for http signature data in the "Signature" header. // more information can be found on https://github.com/go-fed/httpsig -type HTTPSign struct { -} +type HTTPSign struct{} // Name represents the name of auth method func (h *HTTPSign) Name() string { @@ -101,7 +100,7 @@ func VerifyCert(r *http.Request) (*asymkey_model.PublicKey, error) { } for _, principal := range cert.ValidPrincipals { - validpk, err = asymkey_model.SearchPublicKeyByContentExact(principal) + validpk, err = asymkey_model.SearchPublicKeyByContentExact(r.Context(), principal) if err != nil { if asymkey_model.IsErrKeyNotExist(err) { continue From 44cfbfb1575f6a0a9383001d7bbdbeec577083f3 Mon Sep 17 00:00:00 2001 From: Wim Date: Sun, 29 May 2022 21:00:20 +0200 Subject: [PATCH 09/21] Add error when principal doesn't exist in gitea --- services/auth/httpsign.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index 04af47afc69b..ee03ddf1fa7a 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -134,6 +134,11 @@ func VerifyCert(r *http.Request) (*asymkey_model.PublicKey, error) { break } + // validpk will be nil when we didn't find a principal matching the certificate registered in gitea + if validpk == nil { + return validpk, fmt.Errorf("no valid principal found") + } + verifier, err := httpsig.NewVerifier(r) if err != nil { return validpk, fmt.Errorf("httpsig.NewVerifier failed: %s", err) From 437bb86163aa932330a3b31aa6addfeed18829ef Mon Sep 17 00:00:00 2001 From: Wim Date: Mon, 30 May 2022 11:16:37 +0200 Subject: [PATCH 10/21] Marshal auth only once --- services/auth/httpsign.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index ee03ddf1fa7a..eff7287c8e3e 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -111,8 +111,10 @@ func VerifyCert(r *http.Request) (*asymkey_model.PublicKey, error) { c := &ssh.CertChecker{ IsUserAuthority: func(auth ssh.PublicKey) bool { + marshaled := auth.Marshal() + for _, k := range setting.SSH.TrustedUserCAKeysParsed { - if bytes.Equal(auth.Marshal(), k.Marshal()) { + if bytes.Equal(marshaled, k.Marshal()) { return true } } From 0e5560ab8e2d9f445810c85a03dba9953303b510 Mon Sep 17 00:00:00 2001 From: Wim Date: Mon, 30 May 2022 11:18:46 +0200 Subject: [PATCH 11/21] Add doVerify comment --- services/auth/httpsign.go | 1 + 1 file changed, 1 insertion(+) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index eff7287c8e3e..f3f43bce5165 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -155,6 +155,7 @@ func VerifyCert(r *http.Request) (*asymkey_model.PublicKey, error) { return validpk, nil } +// doVerify iterates across the provided public keys attempting the verify the current request against each key in turn func doVerify(verifier httpsig.Verifier, publickeys []ssh.PublicKey) error { verified := false From a91b996d9d3de5876a0f4a63683e638cb3bee21e Mon Sep 17 00:00:00 2001 From: Wim Date: Mon, 30 May 2022 11:23:46 +0200 Subject: [PATCH 12/21] Optimize marshal in ssh module --- modules/ssh/ssh.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/ssh/ssh.go b/modules/ssh/ssh.go index fe3561cefaa3..b0e444ae20d6 100644 --- a/modules/ssh/ssh.go +++ b/modules/ssh/ssh.go @@ -186,8 +186,9 @@ func publicKeyHandler(ctx ssh.Context, key ssh.PublicKey) bool { c := &gossh.CertChecker{ IsUserAuthority: func(auth gossh.PublicKey) bool { + marshaled := auth.Marshal() for _, k := range setting.SSH.TrustedUserCAKeysParsed { - if bytes.Equal(auth.Marshal(), k.Marshal()) { + if bytes.Equal(marshaled, k.Marshal()) { return true } } From 988f425830a2a961451ab60123f1512148eef663 Mon Sep 17 00:00:00 2001 From: Wim Date: Mon, 30 May 2022 11:51:57 +0200 Subject: [PATCH 13/21] Update services/auth/httpsign.go Co-authored-by: zeripath --- services/auth/httpsign.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index f3f43bce5165..38de088c784e 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -59,7 +59,7 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt validpk, err := VerifyCert(req) if err != nil { log.Warn("Failed authentication attempt from %s", req.RemoteAddr) - log.Error("VerifyCert failed: %v", err) + log.Debug("Failed authentication attempt from %s: VerifyCert failed: %v", req.RemoteAddr, err) return nil } From b19b39bff8854da2f0627231a72278975e132c1e Mon Sep 17 00:00:00 2001 From: Wim Date: Mon, 30 May 2022 23:23:30 +0200 Subject: [PATCH 14/21] Add support for normal pubkeys --- services/auth/httpsign.go | 63 +++++++++++++++++++++++++++++++++------ 1 file changed, 54 insertions(+), 9 deletions(-) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index 38de088c784e..9cd4d05e679c 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -52,18 +52,40 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt return nil } - if len(setting.SSH.TrustedUserCAKeys) == 0 { - return nil - } + var ( + u *user_model.User + validpk *asymkey_model.PublicKey + err error + ) + + // Handle SSH certificates + if len(req.Header.Get("x-ssh-certificate")) != 0 { + if len(setting.SSH.TrustedUserCAKeys) == 0 { + return nil + } - validpk, err := VerifyCert(req) - if err != nil { - log.Warn("Failed authentication attempt from %s", req.RemoteAddr) - log.Debug("Failed authentication attempt from %s: VerifyCert failed: %v", req.RemoteAddr, err) - return nil + validpk, err = VerifyCert(req) + if err != nil { + log.Warn("Failed authentication attempt from %s", req.RemoteAddr) + log.Debug("Failed authentication attempt from %s: VerifyCert failed: %v", req.RemoteAddr, err) + return nil + } + } else { + keyID, err := GetKeyID(req) + if err != nil { + log.Debug("GetKeyID failed: %v", err) + return nil + } + + validpk, err = VerifyPubKey(req, keyID) + if err != nil { + log.Warn("Failed authentication attempt from %s", req.RemoteAddr) + log.Debug("Failed authentication attempt from %s: VerifyPubKey failed: %v", req.RemoteAddr, err) + return nil + } } - u, err := user_model.GetUserByID(validpk.OwnerID) + u, err = user_model.GetUserByID(validpk.OwnerID) if err != nil { log.Error("GetUserByID: %v", err) return nil @@ -76,6 +98,19 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt return u } +func VerifyPubKey(r *http.Request, keyID string) (*asymkey_model.PublicKey, error) { + validpk, err := asymkey_model.SearchPublicKey(0, keyID) + if err != nil { + return nil, err + } + + if len(validpk) == 0 { + return nil, fmt.Errorf("no public key found for keyid %s", keyID) + } + + return validpk[0], nil +} + // VerifyCert verifies the validity of the ssh certificate and returns the publickey of the signer // We verify that the certificate is signed with the correct CA // We verify that the http request is signed with the private key (of the public key mentioned in the certificate) @@ -184,3 +219,13 @@ func doVerify(verifier httpsig.Verifier, publickeys []ssh.PublicKey) error { return errors.New("verification failed") } + +// GetKeyID returns the keyid from the httpsignature or an error if doesn't exist +func GetKeyID(r *http.Request) (string, error) { + verifier, err := httpsig.NewVerifier(r) + if err != nil { + return "", fmt.Errorf("httpsig.NewVerifier failed: %s", err) + } + + return verifier.KeyId(), nil +} From 864deef2ce06c979d8f6557e84421c4028c5479e Mon Sep 17 00:00:00 2001 From: zeripath Date: Wed, 1 Jun 2022 20:33:07 +0100 Subject: [PATCH 15/21] Apply suggestions from code review --- services/auth/httpsign.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index 9cd4d05e679c..52c141236d66 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -66,8 +66,8 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt validpk, err = VerifyCert(req) if err != nil { + log.Debug("VerifyCert on request from %s: failed: %v", req.RemoteAddr, err) log.Warn("Failed authentication attempt from %s", req.RemoteAddr) - log.Debug("Failed authentication attempt from %s: VerifyCert failed: %v", req.RemoteAddr, err) return nil } } else { @@ -79,8 +79,8 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt validpk, err = VerifyPubKey(req, keyID) if err != nil { + log.Debug("VerifyPubKey on request from %s: failed: %v", req.RemoteAddr, err) log.Warn("Failed authentication attempt from %s", req.RemoteAddr) - log.Debug("Failed authentication attempt from %s: VerifyPubKey failed: %v", req.RemoteAddr, err) return nil } } From 826eb39036befb1164e4cf49b2d15a0cb5740fd2 Mon Sep 17 00:00:00 2001 From: zeripath Date: Wed, 1 Jun 2022 20:35:43 +0100 Subject: [PATCH 16/21] Apply suggestions from code review --- services/auth/httpsign.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index 52c141236d66..226f087369d0 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -59,7 +59,7 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt ) // Handle SSH certificates - if len(req.Header.Get("x-ssh-certificate")) != 0 { + if len(req.Header.Get("X-Ssh-Certificate")) != 0 { if len(setting.SSH.TrustedUserCAKeys) == 0 { return nil } From c3ad5e8367a38ed7b6beac8f9cd9c862b08c9bd7 Mon Sep 17 00:00:00 2001 From: zeripath Date: Wed, 1 Jun 2022 22:08:22 +0100 Subject: [PATCH 17/21] Properly verify the publickey signing (#1) * Properly verify the publickey signing Signed-off-by: Andrew Thornton * comments in VerifyCert Signed-off-by: Andrew Thornton * parseauthorizedkey instead Signed-off-by: Andrew Thornton * slight renames; Signed-off-by: Andrew Thornton --- services/auth/httpsign.go | 177 ++++++++++++++++++-------------------- 1 file changed, 86 insertions(+), 91 deletions(-) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index 226f087369d0..75a2cb825cdb 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -53,31 +53,25 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt } var ( - u *user_model.User - validpk *asymkey_model.PublicKey - err error + publicKey *asymkey_model.PublicKey + err error ) - // Handle SSH certificates if len(req.Header.Get("X-Ssh-Certificate")) != 0 { + // Handle Signature signed by SSH certificates if len(setting.SSH.TrustedUserCAKeys) == 0 { return nil } - validpk, err = VerifyCert(req) + publicKey, err = VerifyCert(req) if err != nil { log.Debug("VerifyCert on request from %s: failed: %v", req.RemoteAddr, err) log.Warn("Failed authentication attempt from %s", req.RemoteAddr) return nil } } else { - keyID, err := GetKeyID(req) - if err != nil { - log.Debug("GetKeyID failed: %v", err) - return nil - } - - validpk, err = VerifyPubKey(req, keyID) + // Handle Signature signed by Public Key + publicKey, err = VerifyPubKey(req) if err != nil { log.Debug("VerifyPubKey on request from %s: failed: %v", req.RemoteAddr, err) log.Warn("Failed authentication attempt from %s", req.RemoteAddr) @@ -85,7 +79,7 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt } } - u, err = user_model.GetUserByID(validpk.OwnerID) + u, err := user_model.GetUserByID(publicKey.OwnerID) if err != nil { log.Error("GetUserByID: %v", err) return nil @@ -98,134 +92,135 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt return u } -func VerifyPubKey(r *http.Request, keyID string) (*asymkey_model.PublicKey, error) { - validpk, err := asymkey_model.SearchPublicKey(0, keyID) +func VerifyPubKey(r *http.Request) (*asymkey_model.PublicKey, error) { + verifier, err := httpsig.NewVerifier(r) + if err != nil { + return nil, fmt.Errorf("httpsig.NewVerifier failed: %s", err) + } + + keyID := verifier.KeyId() + + publicKeys, err := asymkey_model.SearchPublicKey(0, keyID) if err != nil { return nil, err } - if len(validpk) == 0 { + if len(publicKeys) == 0 { return nil, fmt.Errorf("no public key found for keyid %s", keyID) } - return validpk[0], nil + sshPublicKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(publicKeys[0].Content)) + if err != nil { + return nil, err + } + + if err := doVerify(verifier, []ssh.PublicKey{sshPublicKey}); err != nil { + return nil, err + } + + return publicKeys[0], nil } // VerifyCert verifies the validity of the ssh certificate and returns the publickey of the signer // We verify that the certificate is signed with the correct CA // We verify that the http request is signed with the private key (of the public key mentioned in the certificate) func VerifyCert(r *http.Request) (*asymkey_model.PublicKey, error) { - var validpk *asymkey_model.PublicKey - // Get our certificate from the header bcert, err := base64.RawStdEncoding.DecodeString(r.Header.Get("x-ssh-certificate")) if err != nil { - return validpk, err + return nil, err } pk, err := ssh.ParsePublicKey(bcert) if err != nil { - return validpk, err + return nil, err } // Check if it's really a ssh certificate cert, ok := pk.(*ssh.Certificate) if !ok { - return validpk, fmt.Errorf("no certificate found") + return nil, fmt.Errorf("no certificate found") } - for _, principal := range cert.ValidPrincipals { - validpk, err = asymkey_model.SearchPublicKeyByContentExact(r.Context(), principal) - if err != nil { - if asymkey_model.IsErrKeyNotExist(err) { - continue - } - log.Error("SearchPublicKeyByContentExact: %v", err) - return validpk, err - } + c := &ssh.CertChecker{ + IsUserAuthority: func(auth ssh.PublicKey) bool { + marshaled := auth.Marshal() - c := &ssh.CertChecker{ - IsUserAuthority: func(auth ssh.PublicKey) bool { - marshaled := auth.Marshal() - - for _, k := range setting.SSH.TrustedUserCAKeysParsed { - if bytes.Equal(marshaled, k.Marshal()) { - return true - } + for _, k := range setting.SSH.TrustedUserCAKeysParsed { + if bytes.Equal(marshaled, k.Marshal()) { + return true } + } - return false - }, - } - - // check the CA of the cert - if !c.IsUserAuthority(cert.SignatureKey) { - return validpk, fmt.Errorf("CA check failed") - } - - // validate the cert for this principal - if err := c.CheckCert(principal, cert); err != nil { - return validpk, fmt.Errorf("no valid principal found") - } - - break + return false + }, } - // validpk will be nil when we didn't find a principal matching the certificate registered in gitea - if validpk == nil { - return validpk, fmt.Errorf("no valid principal found") + // check the CA of the cert + if !c.IsUserAuthority(cert.SignatureKey) { + return nil, fmt.Errorf("CA check failed") } + // Create a verifier verifier, err := httpsig.NewVerifier(r) if err != nil { - return validpk, fmt.Errorf("httpsig.NewVerifier failed: %s", err) + return nil, fmt.Errorf("httpsig.NewVerifier failed: %s", err) } - // now verify that we signed this request with the publickey of the cert - err = doVerify(verifier, []ssh.PublicKey{cert.Key}) - if err != nil { - return validpk, err + // now verify that this request was signed with the private key that matches the certificate public key + if err := doVerify(verifier, []ssh.PublicKey{cert.Key}); err != nil { + return nil, err } - return validpk, nil -} - -// doVerify iterates across the provided public keys attempting the verify the current request against each key in turn -func doVerify(verifier httpsig.Verifier, publickeys []ssh.PublicKey) error { - verified := false - - for _, pubkey := range publickeys { - cryptoPubkey := pubkey.(ssh.CryptoPublicKey).CryptoPublicKey() + // Now for each of the certificate valid principals + for _, principal := range cert.ValidPrincipals { - var algo httpsig.Algorithm + // Look in the db for the public key + publicKey, err := asymkey_model.SearchPublicKeyByContentExact(r.Context(), principal) + if err != nil { + if asymkey_model.IsErrKeyNotExist(err) { + // No public key matches this principal - try the next principal + continue + } - switch { - case strings.HasPrefix(pubkey.Type(), "ssh-ed25519"): - algo = httpsig.ED25519 - case strings.HasPrefix(pubkey.Type(), "ssh-rsa"): - algo = httpsig.RSA_SHA1 + // this error will be a db error therefore we can't solve this and we should abort + log.Error("SearchPublicKeyByContentExact: %v", err) + return nil, err } - err := verifier.Verify(cryptoPubkey, algo) - if err == nil { - verified = true - break + // Validate the cert for this principal + if err := c.CheckCert(principal, cert); err != nil { + // however, because principal is a member of ValidPrincipals - if this fails then the certificate itself is invalid + return nil, err } - } - if verified { - return nil + // OK we have a public key for a principal matching a valid certificate whose key has signed this request. + return publicKey, nil } - return errors.New("verification failed") + // No public key matching a principal in the certificate is registered in gitea + return nil, fmt.Errorf("no valid principal found") } -// GetKeyID returns the keyid from the httpsignature or an error if doesn't exist -func GetKeyID(r *http.Request) (string, error) { - verifier, err := httpsig.NewVerifier(r) - if err != nil { - return "", fmt.Errorf("httpsig.NewVerifier failed: %s", err) +// doVerify iterates across the provided public keys attempting the verify the current request against each key in turn +func doVerify(verifier httpsig.Verifier, sshPublicKeys []ssh.PublicKey) error { + for _, publicKey := range sshPublicKeys { + cryptoPubkey := publicKey.(ssh.CryptoPublicKey).CryptoPublicKey() + + var algos []httpsig.Algorithm + + switch { + case strings.HasPrefix(publicKey.Type(), "ssh-ed25519"): + algos = []httpsig.Algorithm{httpsig.ED25519} + case strings.HasPrefix(publicKey.Type(), "ssh-rsa"): + algos = []httpsig.Algorithm{httpsig.RSA_SHA1, httpsig.RSA_SHA256, httpsig.RSA_SHA512} + } + for _, algo := range algos { + if err := verifier.Verify(cryptoPubkey, algo); err == nil { + return nil + } + } } - return verifier.KeyId(), nil + return errors.New("verification failed") } From 81365cfef1d62a251b98d4f64da9df6db564aed9 Mon Sep 17 00:00:00 2001 From: Wim Date: Sat, 4 Jun 2022 00:30:37 +0200 Subject: [PATCH 18/21] Add code review changes --- services/auth/httpsign.go | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index 75a2cb825cdb..67053d2b7773 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -16,7 +16,6 @@ import ( user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" - "code.gitea.io/gitea/modules/web/middleware" "github.com/go-fed/httpsig" "golang.org/x/crypto/ssh" @@ -42,11 +41,6 @@ func (h *HTTPSign) Name() string { // the corresponding user object on successful validation. // Returns nil if header is empty or validation fails. func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) *user_model.User { - // HTTPSign authentication should only fire on API - if !middleware.IsAPIPath(req) { - return nil - } - sigHead := req.Header.Get("Signature") if len(sigHead) == 0 { return nil @@ -174,15 +168,12 @@ func VerifyCert(r *http.Request) (*asymkey_model.PublicKey, error) { // Now for each of the certificate valid principals for _, principal := range cert.ValidPrincipals { - // Look in the db for the public key publicKey, err := asymkey_model.SearchPublicKeyByContentExact(r.Context(), principal) - if err != nil { - if asymkey_model.IsErrKeyNotExist(err) { - // No public key matches this principal - try the next principal - continue - } - + if asymkey_model.IsErrKeyNotExist(err) { + // No public key matches this principal - try the next principal + continue + } else if err != nil { // this error will be a db error therefore we can't solve this and we should abort log.Error("SearchPublicKeyByContentExact: %v", err) return nil, err From 6c00f757891dfed8ea1f362091ac93f5c3ffeb51 Mon Sep 17 00:00:00 2001 From: Wim Date: Sat, 4 Jun 2022 00:32:29 +0200 Subject: [PATCH 19/21] Add integration tests for pub/privkey and certificate --- integrations/api_httpsig_test.go | 132 +++++++++++++++++++++++++++++++ integrations/sqlite.ini.tmpl | 1 + 2 files changed, 133 insertions(+) create mode 100644 integrations/api_httpsig_test.go diff --git a/integrations/api_httpsig_test.go b/integrations/api_httpsig_test.go new file mode 100644 index 000000000000..2761cab1af73 --- /dev/null +++ b/integrations/api_httpsig_test.go @@ -0,0 +1,132 @@ +package integrations + +import ( + "encoding/base64" + "fmt" + "net/http" + "net/url" + "testing" + + api "code.gitea.io/gitea/modules/structs" + "github.com/go-fed/httpsig" + "golang.org/x/crypto/ssh" +) + +const ( + httpsigPrivateKey = `-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABFwAAAAdzc2gtcn +NhAAAAAwEAAQAAAQEAqjmQeb5Eb1xV7qbNf9ErQ0XRvKZWzUsLFhJzZz+Ab7q8WtPs91vQ +fBiypw4i8OTG6WzDcgZaV8Ndxn7iHnIstdA1k89MVG4stydymmwmk9+mrCMNsu5OmdIy9F +AZ61RDcKuf5VG2WKkmeK0VO+OMJIYfE1C6czNeJ6UAmcIOmhGxvjMI83XUO9n0ftwTwayp ++XU5prvKx/fTvlPjbraPNU4OzwPjVLqXBzpoXYhBquPaZYFRVyvfFZLObYsmy+BrsxcloM +l+9w4P0ATJ9njB7dRDL+RrN4uhhYSihqOK4w4vaiOj1+aA0eC0zXunEfLXfGIVQ/FhWcCy +5f72mMiK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TestEnv(t)() + session := loginUser(t, "user1") + token := url.QueryEscape(getTokenForLoggedInUser(t, session)) + keysURL := fmt.Sprintf("/api/v1/user/keys?token=%s", token) + keyType := "ssh-rsa" + keyContent := "AAAAB3NzaC1yc2EAAAADAQABAAABAQCqOZB5vkRvXFXups1/0StDRdG8plbNSwsWEnNnP4Bvurxa0+z3W9B8GLKnDiLw5MbpbMNyBlpXw13GfuIeciy10DWTz0xUbiy3J3KabCaT36asIw2y7k6Z0jL0UBnrVENwq5/lUbZYqSZ4rRU744wkhh8TULpzM14npQCZwg6aEbG+MwjzddQ72fR+3BPBrKn5dTmmu8rH99O+U+Nuto81Tg7PA+NUupcHOmhdiEGq49plgVFXK98Vks5tiybL4GuzFyWgyX73Dg/QBMn2eMHt1EMv5Gs3i6GFhKKGo4rjDi9qI6PX5oDR4LTNe6cR8td8YhVD8WFZwLLl/vaYyIqd" + rawKeyBody := api.CreateKeyOption{ + Title: "test-key", + Key: keyType + " " + keyContent, + } + req := NewRequestWithJSON(t, "POST", keysURL, rawKeyBody) + session.MakeRequest(t, req, http.StatusCreated) + + // parse our private key and create the httpsig request + sshSigner, _ := ssh.ParsePrivateKey([]byte(httpsigPrivateKey)) + keyID := ssh.FingerprintSHA256(sshSigner.PublicKey()) + + // create the request + req = NewRequest(t, "GET", "/api/v1/admin/users") + + signer, _, err := httpsig.NewSSHSigner(sshSigner, httpsig.DigestSha512, []string{httpsig.RequestTarget, "(created)", "(expires)"}, httpsig.Signature, 10) + if err != nil { + t.Fatal(err) + } + + // sign the request + err = signer.SignRequest(keyID, req, nil) + if err != nil { + t.Fatal(err) + } + + // make the request + MakeRequest(t, req, http.StatusOK) +} + +func TestHTTPSigCert(t *testing.T) { + // Add our public key to user1 + defer prepareTestEnv(t)() + session := loginUser(t, "user1") + + csrf := GetCSRF(t, session, "/user/settings/keys") + req := NewRequestWithValues(t, "POST", "/user/settings/keys", map[string]string{ + "_csrf": csrf, + "content": "user1", + "title": "principal", + "type": "principal", + }) + + session.MakeRequest(t, req, http.StatusSeeOther) + pkcert, _, _, _, err := ssh.ParseAuthorizedKey([]byte(httpsigCertificate)) + if err != nil { + t.Fatal(err) + } + + // parse our private key and create the httpsig request + sshSigner, _ := ssh.ParsePrivateKey([]byte(httpsigPrivateKey)) + keyID := "gitea" + + // create our certificate signer using the ssh signer and our certificate + certSigner, err := ssh.NewCertSigner(pkcert.(*ssh.Certificate), sshSigner) + if err != nil { + t.Fatal(err) + } + + // create the request + req = NewRequest(t, "GET", "/api/v1/admin/users") + + // add our cert to the request + certString := base64.RawStdEncoding.EncodeToString(pkcert.(*ssh.Certificate).Marshal()) + req.Header.Add("x-ssh-certificate", certString) + + signer, _, err := httpsig.NewSSHSigner(certSigner, httpsig.DigestSha512, []string{httpsig.RequestTarget, "(created)", "(expires)", "x-ssh-certificate"}, httpsig.Signature, 10) + if err != nil { + t.Fatal(err) + } + + // sign the request + err = signer.SignRequest(keyID, req, nil) + if err != nil { + t.Fatal(err) + } + + // make the request + MakeRequest(t, req, http.StatusOK) +} diff --git a/integrations/sqlite.ini.tmpl b/integrations/sqlite.ini.tmpl index c18014889110..2da7fd65d392 100644 --- a/integrations/sqlite.ini.tmpl +++ b/integrations/sqlite.ini.tmpl @@ -46,6 +46,7 @@ LFS_JWT_SECRET = Tv_MjmZuHqpIY6GFl12ebgkRAMt4RlWt0v4EHKSXO0w APP_DATA_PATH = integrations/gitea-integration-sqlite/data ENABLE_GZIP = true BUILTIN_SSH_SERVER_USER = git +SSH_TRUSTED_USER_CA_KEYS = ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCb4DC1dMFnJ6pXWo7GMxTchtzmJHYzfN6sZ9FAPFR4ijMLfGki+olvOMO5Fql1/yGnGfbELQa1S6y4shSvj/5K+zUFScmEXYf3Gcr87RqilLkyk16RS+cHNB1u87xTHbETaa3nyCJeGQRpd4IQ4NKob745mwDZ7jQBH8AZEng50Oh8y8fi8skBBBzaYp1ilgvzG740L7uex6fHV62myq0SXeCa+oJUjq326FU8y+Vsa32H8A3e7tOgXZPdt2TVNltx2S9H2WO8RMi7LfaSwARNfy1zu+bfR50r6ef8Yx5YKCMz4wWb1SHU1GS800mjOjlInLQORYRNMlSwR1+vLlVDciOqFapDSbj+YOVOawR0R1aqlSKpZkt33DuOBPx9qe6CVnIi7Z+Px/KqM+OLCzlLY/RS+LbxQpDWcfTVRiP+S5qRTcE3M3UioN/e0BE/1+MpX90IGpvVkA63ILYbKEa4bM3ASL7ChTCr6xN5XT+GpVJveFKK1cfNx9ExHI4rzYE= [attachment] PATH = integrations/gitea-integration-sqlite/data/attachments From 40da8bdfa8d3af759096b1a5ca40b9d4771bee92 Mon Sep 17 00:00:00 2001 From: Wim Date: Sat, 4 Jun 2022 14:53:32 +0200 Subject: [PATCH 20/21] Add copyright and blank line --- integrations/api_httpsig_test.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/integrations/api_httpsig_test.go b/integrations/api_httpsig_test.go index 2761cab1af73..7197e9afb992 100644 --- a/integrations/api_httpsig_test.go +++ b/integrations/api_httpsig_test.go @@ -1,3 +1,7 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + package integrations import ( @@ -8,6 +12,7 @@ import ( "testing" api "code.gitea.io/gitea/modules/structs" + "github.com/go-fed/httpsig" "golang.org/x/crypto/ssh" ) From b8d43cdfb95f9cf91cf93cfb51b669245d250c06 Mon Sep 17 00:00:00 2001 From: Wim Date: Sat, 4 Jun 2022 15:07:13 +0200 Subject: [PATCH 21/21] Add SSH_TRUSTED_USER_CA_KEYS to all database templates --- integrations/mssql.ini.tmpl | 1 + integrations/mysql.ini.tmpl | 1 + integrations/mysql8.ini.tmpl | 1 + integrations/pgsql.ini.tmpl | 1 + 4 files changed, 4 insertions(+) diff --git a/integrations/mssql.ini.tmpl b/integrations/mssql.ini.tmpl index b076bb863c72..da15e9ef69ee 100644 --- a/integrations/mssql.ini.tmpl +++ b/integrations/mssql.ini.tmpl @@ -49,6 +49,7 @@ OFFLINE_MODE = false LFS_JWT_SECRET = Tv_MjmZuHqpIY6GFl12ebgkRAMt4RlWt0v4EHKSXO0w APP_DATA_PATH = integrations/gitea-integration-mssql/data BUILTIN_SSH_SERVER_USER = git +SSH_TRUSTED_USER_CA_KEYS = ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCb4DC1dMFnJ6pXWo7GMxTchtzmJHYzfN6sZ9FAPFR4ijMLfGki+olvOMO5Fql1/yGnGfbELQa1S6y4shSvj/5K+zUFScmEXYf3Gcr87RqilLkyk16RS+cHNB1u87xTHbETaa3nyCJeGQRpd4IQ4NKob745mwDZ7jQBH8AZEng50Oh8y8fi8skBBBzaYp1ilgvzG740L7uex6fHV62myq0SXeCa+oJUjq326FU8y+Vsa32H8A3e7tOgXZPdt2TVNltx2S9H2WO8RMi7LfaSwARNfy1zu+bfR50r6ef8Yx5YKCMz4wWb1SHU1GS800mjOjlInLQORYRNMlSwR1+vLlVDciOqFapDSbj+YOVOawR0R1aqlSKpZkt33DuOBPx9qe6CVnIi7Z+Px/KqM+OLCzlLY/RS+LbxQpDWcfTVRiP+S5qRTcE3M3UioN/e0BE/1+MpX90IGpvVkA63ILYbKEa4bM3ASL7ChTCr6xN5XT+GpVJveFKK1cfNx9ExHI4rzYE= [attachment] PATH = integrations/gitea-integration-mssql/data/attachments diff --git a/integrations/mysql.ini.tmpl b/integrations/mysql.ini.tmpl index 6a0fd4ab86b7..4df49336424a 100644 --- a/integrations/mysql.ini.tmpl +++ b/integrations/mysql.ini.tmpl @@ -51,6 +51,7 @@ OFFLINE_MODE = false LFS_START_SERVER = true LFS_JWT_SECRET = Tv_MjmZuHqpIY6GFl12ebgkRAMt4RlWt0v4EHKSXO0w +SSH_TRUSTED_USER_CA_KEYS = ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCb4DC1dMFnJ6pXWo7GMxTchtzmJHYzfN6sZ9FAPFR4ijMLfGki+olvOMO5Fql1/yGnGfbELQa1S6y4shSvj/5K+zUFScmEXYf3Gcr87RqilLkyk16RS+cHNB1u87xTHbETaa3nyCJeGQRpd4IQ4NKob745mwDZ7jQBH8AZEng50Oh8y8fi8skBBBzaYp1ilgvzG740L7uex6fHV62myq0SXeCa+oJUjq326FU8y+Vsa32H8A3e7tOgXZPdt2TVNltx2S9H2WO8RMi7LfaSwARNfy1zu+bfR50r6ef8Yx5YKCMz4wWb1SHU1GS800mjOjlInLQORYRNMlSwR1+vLlVDciOqFapDSbj+YOVOawR0R1aqlSKpZkt33DuOBPx9qe6CVnIi7Z+Px/KqM+OLCzlLY/RS+LbxQpDWcfTVRiP+S5qRTcE3M3UioN/e0BE/1+MpX90IGpvVkA63ILYbKEa4bM3ASL7ChTCr6xN5XT+GpVJveFKK1cfNx9ExHI4rzYE= [lfs] MINIO_BASE_PATH = lfs/ diff --git a/integrations/mysql8.ini.tmpl b/integrations/mysql8.ini.tmpl index 16f8851fe527..4b63dd51a1fd 100644 --- a/integrations/mysql8.ini.tmpl +++ b/integrations/mysql8.ini.tmpl @@ -49,6 +49,7 @@ OFFLINE_MODE = false LFS_JWT_SECRET = Tv_MjmZuHqpIY6GFl12ebgkRAMt4RlWt0v4EHKSXO0w APP_DATA_PATH = integrations/gitea-integration-mysql8/data BUILTIN_SSH_SERVER_USER = git +SSH_TRUSTED_USER_CA_KEYS = ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCb4DC1dMFnJ6pXWo7GMxTchtzmJHYzfN6sZ9FAPFR4ijMLfGki+olvOMO5Fql1/yGnGfbELQa1S6y4shSvj/5K+zUFScmEXYf3Gcr87RqilLkyk16RS+cHNB1u87xTHbETaa3nyCJeGQRpd4IQ4NKob745mwDZ7jQBH8AZEng50Oh8y8fi8skBBBzaYp1ilgvzG740L7uex6fHV62myq0SXeCa+oJUjq326FU8y+Vsa32H8A3e7tOgXZPdt2TVNltx2S9H2WO8RMi7LfaSwARNfy1zu+bfR50r6ef8Yx5YKCMz4wWb1SHU1GS800mjOjlInLQORYRNMlSwR1+vLlVDciOqFapDSbj+YOVOawR0R1aqlSKpZkt33DuOBPx9qe6CVnIi7Z+Px/KqM+OLCzlLY/RS+LbxQpDWcfTVRiP+S5qRTcE3M3UioN/e0BE/1+MpX90IGpvVkA63ILYbKEa4bM3ASL7ChTCr6xN5XT+GpVJveFKK1cfNx9ExHI4rzYE= [attachment] PATH = integrations/gitea-integration-mysql8/data/attachments diff --git a/integrations/pgsql.ini.tmpl b/integrations/pgsql.ini.tmpl index 5c4fbcc82962..5b54a02c9fac 100644 --- a/integrations/pgsql.ini.tmpl +++ b/integrations/pgsql.ini.tmpl @@ -50,6 +50,7 @@ OFFLINE_MODE = false LFS_JWT_SECRET = Tv_MjmZuHqpIY6GFl12ebgkRAMt4RlWt0v4EHKSXO0w APP_DATA_PATH = integrations/gitea-integration-pgsql/data BUILTIN_SSH_SERVER_USER = git +SSH_TRUSTED_USER_CA_KEYS = ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCb4DC1dMFnJ6pXWo7GMxTchtzmJHYzfN6sZ9FAPFR4ijMLfGki+olvOMO5Fql1/yGnGfbELQa1S6y4shSvj/5K+zUFScmEXYf3Gcr87RqilLkyk16RS+cHNB1u87xTHbETaa3nyCJeGQRpd4IQ4NKob745mwDZ7jQBH8AZEng50Oh8y8fi8skBBBzaYp1ilgvzG740L7uex6fHV62myq0SXeCa+oJUjq326FU8y+Vsa32H8A3e7tOgXZPdt2TVNltx2S9H2WO8RMi7LfaSwARNfy1zu+bfR50r6ef8Yx5YKCMz4wWb1SHU1GS800mjOjlInLQORYRNMlSwR1+vLlVDciOqFapDSbj+YOVOawR0R1aqlSKpZkt33DuOBPx9qe6CVnIi7Z+Px/KqM+OLCzlLY/RS+LbxQpDWcfTVRiP+S5qRTcE3M3UioN/e0BE/1+MpX90IGpvVkA63ILYbKEa4bM3ASL7ChTCr6xN5XT+GpVJveFKK1cfNx9ExHI4rzYE= [attachment] PATH = integrations/gitea-integration-pgsql/data/attachments