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 7.1KB

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