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.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. gouuid "github.com/google/uuid"
  16. "github.com/quasoft/websspi"
  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.New().String() + "@localhost.localdomain"
  138. user := &models.User{
  139. Name: username,
  140. Email: email,
  141. KeepEmailPrivate: true,
  142. Passwd: gouuid.New().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. }