code.gitea.io/gitea@v1.22.3/services/auth/httpsign.go (about)

     1  // Copyright 2021 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package auth
     5  
     6  import (
     7  	"bytes"
     8  	"encoding/base64"
     9  	"errors"
    10  	"fmt"
    11  	"net/http"
    12  	"strings"
    13  
    14  	asymkey_model "code.gitea.io/gitea/models/asymkey"
    15  	"code.gitea.io/gitea/models/db"
    16  	user_model "code.gitea.io/gitea/models/user"
    17  	"code.gitea.io/gitea/modules/log"
    18  	"code.gitea.io/gitea/modules/setting"
    19  
    20  	"github.com/go-fed/httpsig"
    21  	"golang.org/x/crypto/ssh"
    22  )
    23  
    24  // Ensure the struct implements the interface.
    25  var (
    26  	_ Method = &HTTPSign{}
    27  )
    28  
    29  // HTTPSign implements the Auth interface and authenticates requests (API requests
    30  // only) by looking for http signature data in the "Signature" header.
    31  // more information can be found on https://github.com/go-fed/httpsig
    32  type HTTPSign struct{}
    33  
    34  // Name represents the name of auth method
    35  func (h *HTTPSign) Name() string {
    36  	return "httpsign"
    37  }
    38  
    39  // Verify extracts and validates HTTPsign from the Signature header of the request and returns
    40  // the corresponding user object on successful validation.
    41  // Returns nil if header is empty or validation fails.
    42  func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) (*user_model.User, error) {
    43  	sigHead := req.Header.Get("Signature")
    44  	if len(sigHead) == 0 {
    45  		return nil, nil
    46  	}
    47  
    48  	var (
    49  		publicKey *asymkey_model.PublicKey
    50  		err       error
    51  	)
    52  
    53  	if len(req.Header.Get("X-Ssh-Certificate")) != 0 {
    54  		// Handle Signature signed by SSH certificates
    55  		if len(setting.SSH.TrustedUserCAKeys) == 0 {
    56  			return nil, nil
    57  		}
    58  
    59  		publicKey, err = VerifyCert(req)
    60  		if err != nil {
    61  			log.Debug("VerifyCert on request from %s: failed: %v", req.RemoteAddr, err)
    62  			log.Warn("Failed authentication attempt from %s", req.RemoteAddr)
    63  			return nil, nil
    64  		}
    65  	} else {
    66  		// Handle Signature signed by Public Key
    67  		publicKey, err = VerifyPubKey(req)
    68  		if err != nil {
    69  			log.Debug("VerifyPubKey on request from %s: failed: %v", req.RemoteAddr, err)
    70  			log.Warn("Failed authentication attempt from %s", req.RemoteAddr)
    71  			return nil, nil
    72  		}
    73  	}
    74  
    75  	u, err := user_model.GetUserByID(req.Context(), publicKey.OwnerID)
    76  	if err != nil {
    77  		log.Error("GetUserByID:  %v", err)
    78  		return nil, err
    79  	}
    80  
    81  	store.GetData()["IsApiToken"] = true
    82  
    83  	log.Trace("HTTP Sign: Logged in user %-v", u)
    84  
    85  	return u, nil
    86  }
    87  
    88  func VerifyPubKey(r *http.Request) (*asymkey_model.PublicKey, error) {
    89  	verifier, err := httpsig.NewVerifier(r)
    90  	if err != nil {
    91  		return nil, fmt.Errorf("httpsig.NewVerifier failed: %s", err)
    92  	}
    93  
    94  	keyID := verifier.KeyId()
    95  
    96  	publicKeys, err := db.Find[asymkey_model.PublicKey](r.Context(), asymkey_model.FindPublicKeyOptions{
    97  		Fingerprint: keyID,
    98  	})
    99  	if err != nil {
   100  		return nil, err
   101  	}
   102  
   103  	if len(publicKeys) == 0 {
   104  		return nil, fmt.Errorf("no public key found for keyid %s", keyID)
   105  	}
   106  
   107  	sshPublicKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(publicKeys[0].Content))
   108  	if err != nil {
   109  		return nil, err
   110  	}
   111  
   112  	if err := doVerify(verifier, []ssh.PublicKey{sshPublicKey}); err != nil {
   113  		return nil, err
   114  	}
   115  
   116  	return publicKeys[0], nil
   117  }
   118  
   119  // VerifyCert verifies the validity of the ssh certificate and returns the publickey of the signer
   120  // We verify that the certificate is signed with the correct CA
   121  // We verify that the http request is signed with the private key (of the public key mentioned in the certificate)
   122  func VerifyCert(r *http.Request) (*asymkey_model.PublicKey, error) {
   123  	// Get our certificate from the header
   124  	bcert, err := base64.RawStdEncoding.DecodeString(r.Header.Get("x-ssh-certificate"))
   125  	if err != nil {
   126  		return nil, err
   127  	}
   128  
   129  	pk, err := ssh.ParsePublicKey(bcert)
   130  	if err != nil {
   131  		return nil, err
   132  	}
   133  
   134  	// Check if it's really a ssh certificate
   135  	cert, ok := pk.(*ssh.Certificate)
   136  	if !ok {
   137  		return nil, fmt.Errorf("no certificate found")
   138  	}
   139  
   140  	c := &ssh.CertChecker{
   141  		IsUserAuthority: func(auth ssh.PublicKey) bool {
   142  			marshaled := auth.Marshal()
   143  
   144  			for _, k := range setting.SSH.TrustedUserCAKeysParsed {
   145  				if bytes.Equal(marshaled, k.Marshal()) {
   146  					return true
   147  				}
   148  			}
   149  
   150  			return false
   151  		},
   152  	}
   153  
   154  	// check the CA of the cert
   155  	if !c.IsUserAuthority(cert.SignatureKey) {
   156  		return nil, fmt.Errorf("CA check failed")
   157  	}
   158  
   159  	// Create a verifier
   160  	verifier, err := httpsig.NewVerifier(r)
   161  	if err != nil {
   162  		return nil, fmt.Errorf("httpsig.NewVerifier failed: %s", err)
   163  	}
   164  
   165  	// now verify that this request was signed with the private key that matches the certificate public key
   166  	if err := doVerify(verifier, []ssh.PublicKey{cert.Key}); err != nil {
   167  		return nil, err
   168  	}
   169  
   170  	// Now for each of the certificate valid principals
   171  	for _, principal := range cert.ValidPrincipals {
   172  		// Look in the db for the public key
   173  		publicKey, err := asymkey_model.SearchPublicKeyByContentExact(r.Context(), principal)
   174  		if asymkey_model.IsErrKeyNotExist(err) {
   175  			// No public key matches this principal - try the next principal
   176  			continue
   177  		} else if err != nil {
   178  			// this error will be a db error therefore we can't solve this and we should abort
   179  			log.Error("SearchPublicKeyByContentExact: %v", err)
   180  			return nil, err
   181  		}
   182  
   183  		// Validate the cert for this principal
   184  		if err := c.CheckCert(principal, cert); err != nil {
   185  			// however, because principal is a member of ValidPrincipals - if this fails then the certificate itself is invalid
   186  			return nil, err
   187  		}
   188  
   189  		// OK we have a public key for a principal matching a valid certificate whose key has signed this request.
   190  		return publicKey, nil
   191  	}
   192  
   193  	// No public key matching a principal in the certificate is registered in gitea
   194  	return nil, fmt.Errorf("no valid principal found")
   195  }
   196  
   197  // doVerify iterates across the provided public keys attempting the verify the current request against each key in turn
   198  func doVerify(verifier httpsig.Verifier, sshPublicKeys []ssh.PublicKey) error {
   199  	for _, publicKey := range sshPublicKeys {
   200  		cryptoPubkey := publicKey.(ssh.CryptoPublicKey).CryptoPublicKey()
   201  
   202  		var algos []httpsig.Algorithm
   203  
   204  		switch {
   205  		case strings.HasPrefix(publicKey.Type(), "ssh-ed25519"):
   206  			algos = []httpsig.Algorithm{httpsig.ED25519}
   207  		case strings.HasPrefix(publicKey.Type(), "ssh-rsa"):
   208  			algos = []httpsig.Algorithm{httpsig.RSA_SHA1, httpsig.RSA_SHA256, httpsig.RSA_SHA512}
   209  		}
   210  		for _, algo := range algos {
   211  			if err := verifier.Verify(cryptoPubkey, algo); err == nil {
   212  				return nil
   213  			}
   214  		}
   215  	}
   216  
   217  	return errors.New("verification failed")
   218  }