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.

237 lines
7.0 KiB

Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
5 years ago
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package sso
  5. import (
  6. "errors"
  7. "reflect"
  8. "strings"
  9. "code.gitea.io/gitea/models"
  10. "code.gitea.io/gitea/modules/base"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/setting"
  13. "gitea.com/macaron/macaron"
  14. "gitea.com/macaron/session"
  15. "github.com/quasoft/websspi"
  16. gouuid "github.com/satori/go.uuid"
  17. )
  18. const (
  19. tplSignIn base.TplName = "user/auth/signin"
  20. )
  21. var (
  22. // sspiAuth is a global instance of the websspi authentication package,
  23. // which is used to avoid acquiring the server credential handle on
  24. // every request
  25. sspiAuth *websspi.Authenticator
  26. // Ensure the struct implements the interface.
  27. _ SingleSignOn = &SSPI{}
  28. )
  29. // SSPI implements the SingleSignOn interface and authenticates requests
  30. // via the built-in SSPI module in Windows for SPNEGO authentication.
  31. // On successful authentication returns a valid user object.
  32. // Returns nil if authentication fails.
  33. type SSPI struct {
  34. }
  35. // Init creates a new global websspi.Authenticator object
  36. func (s *SSPI) Init() error {
  37. config := websspi.NewConfig()
  38. var err error
  39. sspiAuth, err = websspi.New(config)
  40. return err
  41. }
  42. // Free releases resources used by the global websspi.Authenticator object
  43. func (s *SSPI) Free() error {
  44. return sspiAuth.Free()
  45. }
  46. // IsEnabled checks if there is an active SSPI authentication source
  47. func (s *SSPI) IsEnabled() bool {
  48. return models.IsSSPIEnabled()
  49. }
  50. // VerifyAuthData uses SSPI (Windows implementation of SPNEGO) to authenticate the request.
  51. // If authentication is successful, returs the corresponding user object.
  52. // If negotiation should continue or authentication fails, immediately returns a 401 HTTP
  53. // response code, as required by the SPNEGO protocol.
  54. func (s *SSPI) VerifyAuthData(ctx *macaron.Context, sess session.Store) *models.User {
  55. if !s.shouldAuthenticate(ctx) {
  56. return nil
  57. }
  58. cfg, err := s.getConfig()
  59. if err != nil {
  60. log.Error("could not get SSPI config: %v", err)
  61. return nil
  62. }
  63. userInfo, outToken, err := sspiAuth.Authenticate(ctx.Req.Request, ctx.Resp)
  64. if err != nil {
  65. log.Warn("Authentication failed with error: %v\n", err)
  66. sspiAuth.AppendAuthenticateHeader(ctx.Resp, 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. addFlashErr(ctx, ctx.Tr("auth.sspi_auth_failed"))
  71. ctx.Data["EnableOpenIDSignIn"] = setting.Service.EnableOpenIDSignIn
  72. ctx.Data["EnableSSPI"] = true
  73. ctx.HTML(401, string(tplSignIn))
  74. return nil
  75. }
  76. if outToken != "" {
  77. sspiAuth.AppendAuthenticateHeader(ctx.Resp, outToken)
  78. }
  79. username := sanitizeUsername(userInfo.Username, cfg)
  80. if len(username) == 0 {
  81. return nil
  82. }
  83. log.Info("Authenticated as %s\n", username)
  84. user, err := models.GetUserByName(username)
  85. if err != nil {
  86. if !models.IsErrUserNotExist(err) {
  87. log.Error("GetUserByName: %v", err)
  88. return nil
  89. }
  90. if !cfg.AutoCreateUsers {
  91. log.Error("User '%s' not found", username)
  92. return nil
  93. }
  94. user, err = s.newUser(ctx, username, cfg)
  95. if err != nil {
  96. log.Error("CreateUser: %v", err)
  97. return nil
  98. }
  99. }
  100. // Make sure requests to API paths and PWA resources do not create a new session
  101. if !isAPIPath(ctx) && !isAttachmentDownload(ctx) {
  102. handleSignIn(ctx, sess, user)
  103. }
  104. return user
  105. }
  106. // getConfig retrieves the SSPI configuration from login sources
  107. func (s *SSPI) getConfig() (*models.SSPIConfig, error) {
  108. sources, err := models.ActiveLoginSources(models.LoginSSPI)
  109. if err != nil {
  110. return nil, err
  111. }
  112. if len(sources) == 0 {
  113. return nil, errors.New("no active login sources of type SSPI found")
  114. }
  115. if len(sources) > 1 {
  116. return nil, errors.New("more than one active login source of type SSPI found")
  117. }
  118. return sources[0].SSPI(), nil
  119. }
  120. func (s *SSPI) shouldAuthenticate(ctx *macaron.Context) (shouldAuth bool) {
  121. shouldAuth = false
  122. path := strings.TrimSuffix(ctx.Req.URL.Path, "/")
  123. if path == "/user/login" {
  124. if ctx.Req.FormValue("user_name") != "" && ctx.Req.FormValue("password") != "" {
  125. shouldAuth = false
  126. } else if ctx.Req.FormValue("auth_with_sspi") == "1" {
  127. shouldAuth = true
  128. }
  129. } else if isAPIPath(ctx) || isAttachmentDownload(ctx) {
  130. shouldAuth = true
  131. }
  132. return
  133. }
  134. // newUser creates a new user object for the purpose of automatic registration
  135. // and populates its name and email with the information present in request headers.
  136. func (s *SSPI) newUser(ctx *macaron.Context, username string, cfg *models.SSPIConfig) (*models.User, error) {
  137. email := gouuid.NewV4().String() + "@localhost.localdomain"
  138. user := &models.User{
  139. Name: username,
  140. Email: email,
  141. KeepEmailPrivate: true,
  142. Passwd: gouuid.NewV4().String(),
  143. IsActive: cfg.AutoActivateUsers,
  144. Language: cfg.DefaultLanguage,
  145. UseCustomAvatar: true,
  146. Avatar: base.DefaultAvatarLink(),
  147. EmailNotificationsPreference: models.EmailNotificationsDisabled,
  148. }
  149. if err := models.CreateUser(user); err != nil {
  150. return nil, err
  151. }
  152. return user, nil
  153. }
  154. // stripDomainNames removes NETBIOS domain name and separator from down-level logon names
  155. // (eg. "DOMAIN\user" becomes "user"), and removes the UPN suffix (domain name) and separator
  156. // from UPNs (eg. "user@domain.local" becomes "user")
  157. func stripDomainNames(username string) string {
  158. if strings.Contains(username, "\\") {
  159. parts := strings.SplitN(username, "\\", 2)
  160. if len(parts) > 1 {
  161. username = parts[1]
  162. }
  163. } else if strings.Contains(username, "@") {
  164. parts := strings.Split(username, "@")
  165. if len(parts) > 1 {
  166. username = parts[0]
  167. }
  168. }
  169. return username
  170. }
  171. func replaceSeparators(username string, cfg *models.SSPIConfig) string {
  172. newSep := cfg.SeparatorReplacement
  173. username = strings.ReplaceAll(username, "\\", newSep)
  174. username = strings.ReplaceAll(username, "/", newSep)
  175. username = strings.ReplaceAll(username, "@", newSep)
  176. return username
  177. }
  178. func sanitizeUsername(username string, cfg *models.SSPIConfig) string {
  179. if len(username) == 0 {
  180. return ""
  181. }
  182. if cfg.StripDomainNames {
  183. username = stripDomainNames(username)
  184. }
  185. // Replace separators even if we have already stripped the domain name part,
  186. // as the username can contain several separators: eg. "MICROSOFT\useremail@live.com"
  187. username = replaceSeparators(username, cfg)
  188. return username
  189. }
  190. // addFlashErr adds an error message to the Flash object mapped to a macaron.Context
  191. func addFlashErr(ctx *macaron.Context, err string) {
  192. fv := ctx.GetVal(reflect.TypeOf(&session.Flash{}))
  193. if !fv.IsValid() {
  194. return
  195. }
  196. flash, ok := fv.Interface().(*session.Flash)
  197. if !ok {
  198. return
  199. }
  200. flash.Error(err)
  201. ctx.Data["Flash"] = flash
  202. }
  203. // init registers the SSPI auth method as the last method in the list.
  204. // The SSPI plugin is expected to be executed last, as it returns 401 status code if negotiation
  205. // fails (or if negotiation should continue), which would prevent other authentication methods
  206. // to execute at all.
  207. func init() {
  208. Register(&SSPI{})
  209. }