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_windows.go 7.2KB

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