You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

httpsign.go 6.1KB

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