gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package auth
  4. import (
  5. "context"
  6. "errors"
  7. "net/http"
  8. "strings"
  9. "sync"
  10. "code.gitea.io/gitea/models/auth"
  11. "code.gitea.io/gitea/models/db"
  12. user_model "code.gitea.io/gitea/models/user"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/optional"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/templates"
  17. "code.gitea.io/gitea/services/auth/source/sspi"
  18. gitea_context "code.gitea.io/gitea/services/context"
  19. gouuid "github.com/google/uuid"
  20. )
  21. const (
  22. tplSignIn templates.TplName = "user/auth/signin"
  23. )
  24. type SSPIAuth interface {
  25. AppendAuthenticateHeader(w http.ResponseWriter, data string)
  26. Authenticate(r *http.Request, w http.ResponseWriter) (userInfo *SSPIUserInfo, outToken string, err error)
  27. }
  28. var (
  29. sspiAuth SSPIAuth // a global instance of the websspi authenticator to avoid acquiring the server credential handle on every request
  30. sspiAuthOnce sync.Once
  31. sspiAuthErrInit error
  32. // Ensure the struct implements the interface.
  33. _ Method = &SSPI{}
  34. )
  35. // SSPI implements the SingleSignOn interface and authenticates requests
  36. // via the built-in SSPI module in Windows for SPNEGO authentication.
  37. // The SSPI plugin is expected to be executed last, as it returns 401 status code if negotiation
  38. // fails (or if negotiation should continue), which would prevent other authentication methods
  39. // to execute at all.
  40. type SSPI struct{}
  41. // Name represents the name of auth method
  42. func (s *SSPI) Name() string {
  43. return "sspi"
  44. }
  45. // Verify uses SSPI (Windows implementation of SPNEGO) to authenticate the request.
  46. // If authentication is successful, returns the corresponding user object.
  47. // If negotiation should continue or authentication fails, immediately returns a 401 HTTP
  48. // response code, as required by the SPNEGO protocol.
  49. func (s *SSPI) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) (*user_model.User, error) {
  50. sspiAuthOnce.Do(func() { sspiAuthErrInit = sspiAuthInit() })
  51. if sspiAuthErrInit != nil {
  52. return nil, sspiAuthErrInit
  53. }
  54. if !s.shouldAuthenticate(req) {
  55. return nil, nil
  56. }
  57. cfg, err := s.getConfig(req.Context())
  58. if err != nil {
  59. log.Error("could not get SSPI config: %v", err)
  60. return nil, err
  61. }
  62. log.Trace("SSPI Authorization: Attempting to authenticate")
  63. userInfo, outToken, err := sspiAuth.Authenticate(req, w)
  64. if err != nil {
  65. log.Warn("Authentication failed with error: %v\n", err)
  66. sspiAuth.AppendAuthenticateHeader(w, outToken)
  67. // Include the user login page in the 401 response to allow the user
  68. // to login with another authentication method if SSPI authentication
  69. // fails
  70. store.GetData()["Flash"] = map[string]string{
  71. "ErrorMsg": err.Error(),
  72. }
  73. store.GetData()["EnableOpenIDSignIn"] = setting.Service.EnableOpenIDSignIn
  74. store.GetData()["EnableSSPI"] = true
  75. // in this case, the Verify function is called in Gitea's web context
  76. // FIXME: it doesn't look good to render the page here, why not redirect?
  77. gitea_context.GetWebContext(req.Context()).HTML(http.StatusUnauthorized, tplSignIn)
  78. return nil, err
  79. }
  80. if outToken != "" {
  81. sspiAuth.AppendAuthenticateHeader(w, outToken)
  82. }
  83. username := sanitizeUsername(userInfo.Username, cfg)
  84. if len(username) == 0 {
  85. return nil, nil
  86. }
  87. log.Info("Authenticated as %s\n", username)
  88. user, err := user_model.GetUserByName(req.Context(), username)
  89. if err != nil {
  90. if !user_model.IsErrUserNotExist(err) {
  91. log.Error("GetUserByName: %v", err)
  92. return nil, err
  93. }
  94. if !cfg.AutoCreateUsers {
  95. log.Error("User '%s' not found", username)
  96. return nil, nil
  97. }
  98. user, err = s.newUser(req.Context(), username, cfg)
  99. if err != nil {
  100. log.Error("CreateUser: %v", err)
  101. return nil, err
  102. }
  103. }
  104. // Make sure requests to API paths and PWA resources do not create a new session
  105. detector := newAuthPathDetector(req)
  106. if !detector.isAPIPath() && !detector.isAttachmentDownload() {
  107. handleSignIn(w, req, sess, user)
  108. }
  109. log.Trace("SSPI Authorization: Logged in user %-v", user)
  110. return user, nil
  111. }
  112. // getConfig retrieves the SSPI configuration from login sources
  113. func (s *SSPI) getConfig(ctx context.Context) (*sspi.Source, error) {
  114. sources, err := db.Find[auth.Source](ctx, auth.FindSourcesOptions{
  115. IsActive: optional.Some(true),
  116. LoginType: auth.SSPI,
  117. })
  118. if err != nil {
  119. return nil, err
  120. }
  121. if len(sources) == 0 {
  122. return nil, errors.New("no active login sources of type SSPI found")
  123. }
  124. if len(sources) > 1 {
  125. return nil, errors.New("more than one active login source of type SSPI found")
  126. }
  127. return sources[0].Cfg.(*sspi.Source), nil
  128. }
  129. func (s *SSPI) shouldAuthenticate(req *http.Request) (shouldAuth bool) {
  130. shouldAuth = false
  131. path := strings.TrimSuffix(req.URL.Path, "/")
  132. if path == "/user/login" {
  133. if req.FormValue("user_name") != "" && req.FormValue("password") != "" {
  134. shouldAuth = false
  135. } else if req.FormValue("auth_with_sspi") == "1" {
  136. shouldAuth = true
  137. }
  138. } else {
  139. detector := newAuthPathDetector(req)
  140. shouldAuth = detector.isAPIPath() || detector.isAttachmentDownload()
  141. }
  142. return shouldAuth
  143. }
  144. // newUser creates a new user object for the purpose of automatic registration
  145. // and populates its name and email with the information present in request headers.
  146. func (s *SSPI) newUser(ctx context.Context, username string, cfg *sspi.Source) (*user_model.User, error) {
  147. email := gouuid.New().String() + "@localhost.localdomain"
  148. user := &user_model.User{
  149. Name: username,
  150. Email: email,
  151. Language: cfg.DefaultLanguage,
  152. }
  153. emailNotificationPreference := user_model.EmailNotificationsDisabled
  154. overwriteDefault := &user_model.CreateUserOverwriteOptions{
  155. IsActive: optional.Some(cfg.AutoActivateUsers),
  156. KeepEmailPrivate: optional.Some(true),
  157. EmailNotificationsPreference: &emailNotificationPreference,
  158. }
  159. if err := user_model.CreateUser(ctx, user, &user_model.Meta{}, overwriteDefault); err != nil {
  160. return nil, err
  161. }
  162. return user, nil
  163. }
  164. // stripDomainNames removes NETBIOS domain name and separator from down-level logon names
  165. // (eg. "DOMAIN\user" becomes "user"), and removes the UPN suffix (domain name) and separator
  166. // from UPNs (eg. "user@domain.local" becomes "user")
  167. func stripDomainNames(username string) string {
  168. if strings.Contains(username, "\\") {
  169. parts := strings.SplitN(username, "\\", 2)
  170. if len(parts) > 1 {
  171. username = parts[1]
  172. }
  173. } else if strings.Contains(username, "@") {
  174. parts := strings.Split(username, "@")
  175. if len(parts) > 1 {
  176. username = parts[0]
  177. }
  178. }
  179. return username
  180. }
  181. func replaceSeparators(username string, cfg *sspi.Source) string {
  182. newSep := cfg.SeparatorReplacement
  183. username = strings.ReplaceAll(username, "\\", newSep)
  184. username = strings.ReplaceAll(username, "/", newSep)
  185. username = strings.ReplaceAll(username, "@", newSep)
  186. return username
  187. }
  188. func sanitizeUsername(username string, cfg *sspi.Source) string {
  189. if len(username) == 0 {
  190. return ""
  191. }
  192. if cfg.StripDomainNames {
  193. username = stripDomainNames(username)
  194. }
  195. // Replace separators even if we have already stripped the domain name part,
  196. // as the username can contain several separators: eg. "MICROSOFT\useremail@live.com"
  197. username = replaceSeparators(username, cfg)
  198. return username
  199. }