-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Implement http signatures support for the API #17565
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 20 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
4effd55
Implement http signatures support for the API
42wim 465a7f4
Return nil on error
42wim c8c344e
Add Failed authentication attempt warning
42wim 8612a72
Fix upstream api changes to user_model
42wim b0005d5
Fix upstream api changes to asymkey_model
42wim 8377c7f
Merge branch 'main' into httpsign
42wim c86617b
Apply suggestions from code review
42wim 0cf37bb
Apply more suggestions from code review
42wim b7dc05c
Merge branch 'main' into HEAD
42wim 98b5bd5
Fix upstream main API changes
42wim 44cfbfb
Add error when principal doesn't exist in gitea
42wim 437bb86
Marshal auth only once
42wim 0e5560a
Add doVerify comment
42wim a91b996
Optimize marshal in ssh module
42wim 988f425
Update services/auth/httpsign.go
42wim b19b39b
Add support for normal pubkeys
42wim a8aa576
Merge branch 'main' into httpsign
6543 864deef
Apply suggestions from code review
zeripath 826eb39
Apply suggestions from code review
zeripath c3ad5e8
Properly verify the publickey signing (#1)
zeripath 81365cf
Add code review changes
42wim 6c00f75
Add integration tests for pub/privkey and certificate
42wim 40da8bd
Add copyright and blank line
42wim b8d43cd
Add SSH_TRUSTED_USER_CA_KEYS to all database templates
42wim 2870bc0
Merge branch 'main' into httpsign
lunny b723c85
Merge branch 'main' into httpsign
lunny fa92d97
Merge branch 'main' into httpsign
lunny File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,226 @@ | ||
// 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" | ||
|
||
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" | ||
"code.gitea.io/gitea/modules/web/middleware" | ||
|
||
"github.com/go-fed/httpsig" | ||
42wim marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"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) *user_model.User { | ||
// HTTPSign authentication should only fire on API | ||
if !middleware.IsAPIPath(req) { | ||
42wim marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return nil | ||
} | ||
|
||
sigHead := req.Header.Get("Signature") | ||
zeripath marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if len(sigHead) == 0 { | ||
return nil | ||
} | ||
|
||
var ( | ||
publicKey *asymkey_model.PublicKey | ||
err error | ||
) | ||
|
||
if len(req.Header.Get("X-Ssh-Certificate")) != 0 { | ||
// Handle Signature signed by SSH certificates | ||
if len(setting.SSH.TrustedUserCAKeys) == 0 { | ||
return nil | ||
} | ||
|
||
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 { | ||
// 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) | ||
return nil | ||
} | ||
} | ||
|
||
u, err := user_model.GetUserByID(publicKey.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 | ||
} | ||
|
||
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(publicKeys) == 0 { | ||
return nil, fmt.Errorf("no public key found for keyid %s", keyID) | ||
} | ||
|
||
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) { | ||
// Get our certificate from the header | ||
bcert, err := base64.RawStdEncoding.DecodeString(r.Header.Get("x-ssh-certificate")) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
pk, err := ssh.ParsePublicKey(bcert) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
// Check if it's really a ssh certificate | ||
cert, ok := pk.(*ssh.Certificate) | ||
if !ok { | ||
return nil, fmt.Errorf("no certificate found") | ||
} | ||
|
||
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 | ||
} | ||
} | ||
|
||
return false | ||
}, | ||
} | ||
|
||
// 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 nil, fmt.Errorf("httpsig.NewVerifier failed: %s", 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 | ||
} | ||
|
||
// 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) { | ||
42wim marked this conversation as resolved.
Show resolved
Hide resolved
|
||
// No public key matches this principal - try the next principal | ||
continue | ||
} | ||
|
||
// 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 | ||
} | ||
|
||
// 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 | ||
} | ||
|
||
// OK we have a public key for a principal matching a valid certificate whose key has signed this request. | ||
return publicKey, nil | ||
} | ||
|
||
// No public key matching a principal in the certificate is registered in gitea | ||
return nil, fmt.Errorf("no valid principal found") | ||
} | ||
|
||
// 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 errors.New("verification failed") | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.