otp.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. package user
  2. import (
  3. "bytes"
  4. "crypto/sha1"
  5. "encoding/base64"
  6. "encoding/hex"
  7. "fmt"
  8. "github.com/0xJacky/Nginx-UI/api"
  9. "github.com/0xJacky/Nginx-UI/internal/crypto"
  10. "github.com/0xJacky/Nginx-UI/internal/user"
  11. "github.com/0xJacky/Nginx-UI/model"
  12. "github.com/0xJacky/Nginx-UI/query"
  13. "github.com/0xJacky/Nginx-UI/settings"
  14. "github.com/gin-gonic/gin"
  15. "github.com/pquerna/otp"
  16. "github.com/pquerna/otp/totp"
  17. "image/jpeg"
  18. "net/http"
  19. "strings"
  20. )
  21. func GenerateTOTP(c *gin.Context) {
  22. u := api.CurrentUser(c)
  23. issuer := fmt.Sprintf("Nginx UI %s", settings.ServerSettings.Name)
  24. issuer = strings.TrimSpace(issuer)
  25. otpOpts := totp.GenerateOpts{
  26. Issuer: issuer,
  27. AccountName: u.Name,
  28. Period: 30, // seconds
  29. Digits: otp.DigitsSix,
  30. Algorithm: otp.AlgorithmSHA1,
  31. }
  32. otpKey, err := totp.Generate(otpOpts)
  33. if err != nil {
  34. api.ErrHandler(c, err)
  35. return
  36. }
  37. ciphertext, err := crypto.AesEncrypt([]byte(otpKey.Secret()))
  38. if err != nil {
  39. api.ErrHandler(c, err)
  40. return
  41. }
  42. qrCode, err := otpKey.Image(512, 512)
  43. if err != nil {
  44. api.ErrHandler(c, err)
  45. return
  46. }
  47. // Encode the image to a buffer
  48. var buf []byte
  49. buffer := bytes.NewBuffer(buf)
  50. err = jpeg.Encode(buffer, qrCode, nil)
  51. if err != nil {
  52. fmt.Println("Error encoding image:", err)
  53. return
  54. }
  55. // Convert the buffer to a base64 string
  56. base64Str := "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(buffer.Bytes())
  57. c.JSON(http.StatusOK, gin.H{
  58. "secret": base64.StdEncoding.EncodeToString(ciphertext),
  59. "qr_code": base64Str,
  60. })
  61. }
  62. func EnrollTOTP(c *gin.Context) {
  63. cUser := api.CurrentUser(c)
  64. if cUser.EnabledOTP() {
  65. c.JSON(http.StatusBadRequest, gin.H{
  66. "message": "User already enrolled",
  67. })
  68. return
  69. }
  70. if settings.ServerSettings.Demo {
  71. c.JSON(http.StatusBadRequest, gin.H{
  72. "message": "This feature is disabled in demo mode",
  73. })
  74. return
  75. }
  76. var json struct {
  77. Secret string `json:"secret" binding:"required"`
  78. Passcode string `json:"passcode" binding:"required"`
  79. }
  80. if !api.BindAndValid(c, &json) {
  81. return
  82. }
  83. secret, err := base64.StdEncoding.DecodeString(json.Secret)
  84. if err != nil {
  85. api.ErrHandler(c, err)
  86. return
  87. }
  88. decrypted, err := crypto.AesDecrypt(secret)
  89. if err != nil {
  90. api.ErrHandler(c, err)
  91. return
  92. }
  93. if ok := totp.Validate(json.Passcode, string(decrypted)); !ok {
  94. c.JSON(http.StatusNotAcceptable, gin.H{
  95. "message": "Invalid passcode",
  96. })
  97. return
  98. }
  99. ciphertext, err := crypto.AesEncrypt(decrypted)
  100. if err != nil {
  101. api.ErrHandler(c, err)
  102. return
  103. }
  104. u := query.Auth
  105. _, err = u.Where(u.ID.Eq(cUser.ID)).Update(u.OTPSecret, ciphertext)
  106. if err != nil {
  107. api.ErrHandler(c, err)
  108. return
  109. }
  110. recoveryCode := sha1.Sum(ciphertext)
  111. c.JSON(http.StatusOK, gin.H{
  112. "message": "ok",
  113. "recovery_code": hex.EncodeToString(recoveryCode[:]),
  114. })
  115. }
  116. func ResetOTP(c *gin.Context) {
  117. var json struct {
  118. RecoveryCode string `json:"recovery_code"`
  119. }
  120. if !api.BindAndValid(c, &json) {
  121. return
  122. }
  123. recoverCode, err := hex.DecodeString(json.RecoveryCode)
  124. if err != nil {
  125. api.ErrHandler(c, err)
  126. return
  127. }
  128. cUser := api.CurrentUser(c)
  129. k := sha1.Sum(cUser.OTPSecret)
  130. if !bytes.Equal(k[:], recoverCode) {
  131. c.JSON(http.StatusBadRequest, gin.H{
  132. "message": "Invalid recovery code",
  133. })
  134. return
  135. }
  136. u := query.Auth
  137. _, err = u.Where(u.ID.Eq(cUser.ID)).UpdateSimple(u.OTPSecret.Null())
  138. if err != nil {
  139. api.ErrHandler(c, err)
  140. return
  141. }
  142. c.JSON(http.StatusOK, gin.H{
  143. "message": "ok",
  144. })
  145. }
  146. func OTPStatus(c *gin.Context) {
  147. status := false
  148. u, ok := c.Get("user")
  149. if ok {
  150. status = u.(*model.Auth).EnabledOTP()
  151. }
  152. c.JSON(http.StatusOK, gin.H{
  153. "status": status,
  154. })
  155. }
  156. func SecureSessionStatus(c *gin.Context) {
  157. u, ok := c.Get("user")
  158. if !ok || !u.(*model.Auth).EnabledOTP() {
  159. c.JSON(http.StatusOK, gin.H{
  160. "status": false,
  161. })
  162. return
  163. }
  164. ssid := c.GetHeader("X-Secure-Session-ID")
  165. if ssid == "" {
  166. ssid = c.Query("X-Secure-Session-ID")
  167. }
  168. if ssid == "" {
  169. c.JSON(http.StatusOK, gin.H{
  170. "status": false,
  171. })
  172. return
  173. }
  174. if user.VerifySecureSessionID(ssid, u.(*model.Auth).ID) {
  175. c.JSON(http.StatusOK, gin.H{
  176. "status": true,
  177. })
  178. return
  179. }
  180. c.JSON(http.StatusOK, gin.H{
  181. "status": false,
  182. })
  183. }
  184. func StartSecure2FASession(c *gin.Context) {
  185. var json struct {
  186. OTP string `json:"otp"`
  187. RecoveryCode string `json:"recovery_code"`
  188. }
  189. if !api.BindAndValid(c, &json) {
  190. return
  191. }
  192. u := api.CurrentUser(c)
  193. if !u.EnabledOTP() {
  194. c.JSON(http.StatusBadRequest, gin.H{
  195. "message": "User not configured with 2FA",
  196. })
  197. return
  198. }
  199. if json.OTP == "" && json.RecoveryCode == "" {
  200. c.JSON(http.StatusBadRequest, LoginResponse{
  201. Message: "The user has enabled 2FA",
  202. })
  203. return
  204. }
  205. if err := user.VerifyOTP(u, json.OTP, json.RecoveryCode); err != nil {
  206. c.JSON(http.StatusBadRequest, LoginResponse{
  207. Message: "Invalid 2FA or recovery code",
  208. })
  209. return
  210. }
  211. sessionId := user.SetSecureSessionID(u.ID)
  212. c.JSON(http.StatusOK, gin.H{
  213. "session_id": sessionId,
  214. })
  215. }