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.

sspi.go 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. user_model "code.gitea.io/gitea/models/user"
  12. "code.gitea.io/gitea/modules/base"
  13. gitea_context "code.gitea.io/gitea/modules/context"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/util"
  17. "code.gitea.io/gitea/modules/web/middleware"
  18. "code.gitea.io/gitea/services/auth/source/sspi"
  19. gouuid "github.com/google/uuid"
  20. )
  21. const (
  22. tplSignIn base.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()
  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).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. if !middleware.IsAPIPath(req) && !isAttachmentDownload(req) {
  106. handleSignIn(w, req, sess, user)
  107. }
  108. log.Trace("SSPI Authorization: Logged in user %-v", user)
  109. return user, nil
  110. }
  111. // getConfig retrieves the SSPI configuration from login sources
  112. func (s *SSPI) getConfig() (*sspi.Source, error) {
  113. sources, err := auth.ActiveSources(auth.SSPI)
  114. if err != nil {
  115. return nil, err
  116. }
  117. if len(sources) == 0 {
  118. return nil, errors.New("no active login sources of type SSPI found")
  119. }
  120. if len(sources) > 1 {
  121. return nil, errors.New("more than one active login source of type SSPI found")
  122. }
  123. return sources[0].Cfg.(*sspi.Source), nil
  124. }
  125. func (s *SSPI) shouldAuthenticate(req *http.Request) (shouldAuth bool) {
  126. shouldAuth = false
  127. path := strings.TrimSuffix(req.URL.Path, "/")
  128. if path == "/user/login" {
  129. if req.FormValue("user_name") != "" && req.FormValue("password") != "" {
  130. shouldAuth = false
  131. } else if req.FormValue("auth_with_sspi") == "1" {
  132. shouldAuth = true
  133. }
  134. } else if middleware.IsAPIPath(req) || isAttachmentDownload(req) {
  135. shouldAuth = true
  136. }
  137. return shouldAuth
  138. }
  139. // newUser creates a new user object for the purpose of automatic registration
  140. // and populates its name and email with the information present in request headers.
  141. func (s *SSPI) newUser(ctx context.Context, username string, cfg *sspi.Source) (*user_model.User, error) {
  142. email := gouuid.New().String() + "@localhost.localdomain"
  143. user := &user_model.User{
  144. Name: username,
  145. Email: email,
  146. Language: cfg.DefaultLanguage,
  147. }
  148. emailNotificationPreference := user_model.EmailNotificationsDisabled
  149. overwriteDefault := &user_model.CreateUserOverwriteOptions{
  150. IsActive: util.OptionalBoolOf(cfg.AutoActivateUsers),
  151. KeepEmailPrivate: util.OptionalBoolTrue,
  152. EmailNotificationsPreference: &emailNotificationPreference,
  153. }
  154. if err := user_model.CreateUser(ctx, user, overwriteDefault); err != nil {
  155. return nil, err
  156. }
  157. return user, nil
  158. }
  159. // stripDomainNames removes NETBIOS domain name and separator from down-level logon names
  160. // (eg. "DOMAIN\user" becomes "user"), and removes the UPN suffix (domain name) and separator
  161. // from UPNs (eg. "user@domain.local" becomes "user")
  162. func stripDomainNames(username string) string {
  163. if strings.Contains(username, "\\") {
  164. parts := strings.SplitN(username, "\\", 2)
  165. if len(parts) > 1 {
  166. username = parts[1]
  167. }
  168. } else if strings.Contains(username, "@") {
  169. parts := strings.Split(username, "@")
  170. if len(parts) > 1 {
  171. username = parts[0]
  172. }
  173. }
  174. return username
  175. }
  176. func replaceSeparators(username string, cfg *sspi.Source) string {
  177. newSep := cfg.SeparatorReplacement
  178. username = strings.ReplaceAll(username, "\\", newSep)
  179. username = strings.ReplaceAll(username, "/", newSep)
  180. username = strings.ReplaceAll(username, "@", newSep)
  181. return username
  182. }
  183. func sanitizeUsername(username string, cfg *sspi.Source) string {
  184. if len(username) == 0 {
  185. return ""
  186. }
  187. if cfg.StripDomainNames {
  188. username = stripDomainNames(username)
  189. }
  190. // Replace separators even if we have already stripped the domain name part,
  191. // as the username can contain several separators: eg. "MICROSOFT\useremail@live.com"
  192. username = replaceSeparators(username, cfg)
  193. return username
  194. }