You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

security_twofa.go 7.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package setting
  6. import (
  7. "bytes"
  8. "encoding/base64"
  9. "html/template"
  10. "image/png"
  11. "strings"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/auth"
  14. "code.gitea.io/gitea/modules/context"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "github.com/pquerna/otp"
  18. "github.com/pquerna/otp/totp"
  19. )
  20. // RegenerateScratchTwoFactor regenerates the user's 2FA scratch code.
  21. func RegenerateScratchTwoFactor(ctx *context.Context) {
  22. ctx.Data["Title"] = ctx.Tr("settings")
  23. ctx.Data["PageIsSettingsSecurity"] = true
  24. t, err := models.GetTwoFactorByUID(ctx.User.ID)
  25. if err != nil {
  26. if models.IsErrTwoFactorNotEnrolled(err) {
  27. ctx.Flash.Error(ctx.Tr("setting.twofa_not_enrolled"))
  28. ctx.Redirect(setting.AppSubURL + "/user/settings/security")
  29. }
  30. ctx.ServerError("SettingsTwoFactor: Failed to GetTwoFactorByUID", err)
  31. return
  32. }
  33. token, err := t.GenerateScratchToken()
  34. if err != nil {
  35. ctx.ServerError("SettingsTwoFactor: Failed to GenerateScratchToken", err)
  36. return
  37. }
  38. if err = models.UpdateTwoFactor(t); err != nil {
  39. ctx.ServerError("SettingsTwoFactor: Failed to UpdateTwoFactor", err)
  40. return
  41. }
  42. ctx.Flash.Success(ctx.Tr("settings.twofa_scratch_token_regenerated", token))
  43. ctx.Redirect(setting.AppSubURL + "/user/settings/security")
  44. }
  45. // DisableTwoFactor deletes the user's 2FA settings.
  46. func DisableTwoFactor(ctx *context.Context) {
  47. ctx.Data["Title"] = ctx.Tr("settings")
  48. ctx.Data["PageIsSettingsSecurity"] = true
  49. t, err := models.GetTwoFactorByUID(ctx.User.ID)
  50. if err != nil {
  51. if models.IsErrTwoFactorNotEnrolled(err) {
  52. ctx.Flash.Error(ctx.Tr("setting.twofa_not_enrolled"))
  53. ctx.Redirect(setting.AppSubURL + "/user/settings/security")
  54. }
  55. ctx.ServerError("SettingsTwoFactor: Failed to GetTwoFactorByUID", err)
  56. return
  57. }
  58. if err = models.DeleteTwoFactorByID(t.ID, ctx.User.ID); err != nil {
  59. if models.IsErrTwoFactorNotEnrolled(err) {
  60. // There is a potential DB race here - we must have been disabled by another request in the intervening period
  61. ctx.Flash.Success(ctx.Tr("settings.twofa_disabled"))
  62. ctx.Redirect(setting.AppSubURL + "/user/settings/security")
  63. }
  64. ctx.ServerError("SettingsTwoFactor: Failed to DeleteTwoFactorByID", err)
  65. return
  66. }
  67. ctx.Flash.Success(ctx.Tr("settings.twofa_disabled"))
  68. ctx.Redirect(setting.AppSubURL + "/user/settings/security")
  69. }
  70. func twofaGenerateSecretAndQr(ctx *context.Context) bool {
  71. var otpKey *otp.Key
  72. var err error
  73. uri := ctx.Session.Get("twofaUri")
  74. if uri != nil {
  75. otpKey, err = otp.NewKeyFromURL(uri.(string))
  76. if err != nil {
  77. ctx.ServerError("SettingsTwoFactor: Failed NewKeyFromURL: ", err)
  78. return false
  79. }
  80. }
  81. // Filter unsafe character ':' in issuer
  82. issuer := strings.Replace(setting.AppName+" ("+setting.Domain+")", ":", "", -1)
  83. if otpKey == nil {
  84. otpKey, err = totp.Generate(totp.GenerateOpts{
  85. SecretSize: 40,
  86. Issuer: issuer,
  87. AccountName: ctx.User.Name,
  88. })
  89. if err != nil {
  90. ctx.ServerError("SettingsTwoFactor: totpGenerate Failed", err)
  91. return false
  92. }
  93. }
  94. ctx.Data["TwofaSecret"] = otpKey.Secret()
  95. img, err := otpKey.Image(320, 240)
  96. if err != nil {
  97. ctx.ServerError("SettingsTwoFactor: otpKey image generation failed", err)
  98. return false
  99. }
  100. var imgBytes bytes.Buffer
  101. if err = png.Encode(&imgBytes, img); err != nil {
  102. ctx.ServerError("SettingsTwoFactor: otpKey png encoding failed", err)
  103. return false
  104. }
  105. ctx.Data["QrUri"] = template.URL("data:image/png;base64," + base64.StdEncoding.EncodeToString(imgBytes.Bytes()))
  106. if err := ctx.Session.Set("twofaSecret", otpKey.Secret()); err != nil {
  107. ctx.ServerError("SettingsTwoFactor: Failed to set session for twofaSecret", err)
  108. return false
  109. }
  110. if err := ctx.Session.Set("twofaUri", otpKey.String()); err != nil {
  111. ctx.ServerError("SettingsTwoFactor: Failed to set session for twofaUri", err)
  112. return false
  113. }
  114. // Here we're just going to try to release the session early
  115. if err := ctx.Session.Release(); err != nil {
  116. // we'll tolerate errors here as they *should* get saved elsewhere
  117. log.Error("Unable to save changes to the session: %v", err)
  118. }
  119. return true
  120. }
  121. // EnrollTwoFactor shows the page where the user can enroll into 2FA.
  122. func EnrollTwoFactor(ctx *context.Context) {
  123. ctx.Data["Title"] = ctx.Tr("settings")
  124. ctx.Data["PageIsSettingsSecurity"] = true
  125. t, err := models.GetTwoFactorByUID(ctx.User.ID)
  126. if t != nil {
  127. // already enrolled - we should redirect back!
  128. log.Warn("Trying to re-enroll %-v in twofa when already enrolled", ctx.User)
  129. ctx.Flash.Error(ctx.Tr("setting.twofa_is_enrolled"))
  130. ctx.Redirect(setting.AppSubURL + "/user/settings/security")
  131. return
  132. }
  133. if err != nil && !models.IsErrTwoFactorNotEnrolled(err) {
  134. ctx.ServerError("SettingsTwoFactor: GetTwoFactorByUID", err)
  135. return
  136. }
  137. if !twofaGenerateSecretAndQr(ctx) {
  138. return
  139. }
  140. ctx.HTML(200, tplSettingsTwofaEnroll)
  141. }
  142. // EnrollTwoFactorPost handles enrolling the user into 2FA.
  143. func EnrollTwoFactorPost(ctx *context.Context, form auth.TwoFactorAuthForm) {
  144. ctx.Data["Title"] = ctx.Tr("settings")
  145. ctx.Data["PageIsSettingsSecurity"] = true
  146. t, err := models.GetTwoFactorByUID(ctx.User.ID)
  147. if t != nil {
  148. // already enrolled
  149. ctx.Flash.Error(ctx.Tr("setting.twofa_is_enrolled"))
  150. ctx.Redirect(setting.AppSubURL + "/user/settings/security")
  151. return
  152. }
  153. if err != nil && !models.IsErrTwoFactorNotEnrolled(err) {
  154. ctx.ServerError("SettingsTwoFactor: Failed to check if already enrolled with GetTwoFactorByUID", err)
  155. return
  156. }
  157. if ctx.HasError() {
  158. if !twofaGenerateSecretAndQr(ctx) {
  159. return
  160. }
  161. ctx.HTML(200, tplSettingsTwofaEnroll)
  162. return
  163. }
  164. secret := ctx.Session.Get("twofaSecret").(string)
  165. if !totp.Validate(form.Passcode, secret) {
  166. if !twofaGenerateSecretAndQr(ctx) {
  167. return
  168. }
  169. ctx.Flash.Error(ctx.Tr("settings.passcode_invalid"))
  170. ctx.HTML(200, tplSettingsTwofaEnroll)
  171. return
  172. }
  173. t = &models.TwoFactor{
  174. UID: ctx.User.ID,
  175. }
  176. err = t.SetSecret(secret)
  177. if err != nil {
  178. ctx.ServerError("SettingsTwoFactor: Failed to set secret", err)
  179. return
  180. }
  181. token, err := t.GenerateScratchToken()
  182. if err != nil {
  183. ctx.ServerError("SettingsTwoFactor: Failed to generate scratch token", err)
  184. return
  185. }
  186. // Now we have to delete the secrets - because if we fail to insert then it's highly likely that they have already been used
  187. // If we can detect the unique constraint failure below we can move this to after the NewTwoFactor
  188. if err := ctx.Session.Delete("twofaSecret"); err != nil {
  189. // tolerate this failure - it's more important to continue
  190. log.Error("Unable to delete twofaSecret from the session: Error: %v", err)
  191. }
  192. if err := ctx.Session.Delete("twofaUri"); err != nil {
  193. // tolerate this failure - it's more important to continue
  194. log.Error("Unable to delete twofaUri from the session: Error: %v", err)
  195. }
  196. if err := ctx.Session.Release(); err != nil {
  197. // tolerate this failure - it's more important to continue
  198. log.Error("Unable to save changes to the session: %v", err)
  199. }
  200. if err = models.NewTwoFactor(t); err != nil {
  201. // FIXME: We need to handle a unique constraint fail here it's entirely possible that another request has beaten us.
  202. // If there is a unique constraint fail we should just tolerate the error
  203. ctx.ServerError("SettingsTwoFactor: Failed to save two factor", err)
  204. return
  205. }
  206. ctx.Flash.Success(ctx.Tr("settings.twofa_enrolled", token))
  207. ctx.Redirect(setting.AppSubURL + "/user/settings/security")
  208. }