gitea源码

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