api_user.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. // Copyright (C) 2019-2022 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package httpd
  15. import (
  16. "context"
  17. "fmt"
  18. "net/http"
  19. "strconv"
  20. "time"
  21. "github.com/go-chi/render"
  22. "github.com/sftpgo/sdk"
  23. "github.com/drakkan/sftpgo/v2/internal/common"
  24. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  25. "github.com/drakkan/sftpgo/v2/internal/kms"
  26. "github.com/drakkan/sftpgo/v2/internal/smtp"
  27. "github.com/drakkan/sftpgo/v2/internal/util"
  28. "github.com/drakkan/sftpgo/v2/internal/vfs"
  29. )
  30. func getUsers(w http.ResponseWriter, r *http.Request) {
  31. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  32. limit, offset, order, err := getSearchFilters(w, r)
  33. if err != nil {
  34. return
  35. }
  36. claims, err := getTokenClaims(r)
  37. if err != nil || claims.Username == "" {
  38. sendAPIResponse(w, r, err, "Invalid token claims", http.StatusBadRequest)
  39. return
  40. }
  41. users, err := dataprovider.GetUsers(limit, offset, order, claims.Role)
  42. if err == nil {
  43. render.JSON(w, r, users)
  44. } else {
  45. sendAPIResponse(w, r, err, "", http.StatusInternalServerError)
  46. }
  47. }
  48. func getUserByUsername(w http.ResponseWriter, r *http.Request) {
  49. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  50. claims, err := getTokenClaims(r)
  51. if err != nil || claims.Username == "" {
  52. sendAPIResponse(w, r, err, "Invalid token claims", http.StatusBadRequest)
  53. return
  54. }
  55. username := getURLParam(r, "username")
  56. renderUser(w, r, username, claims.Role, http.StatusOK)
  57. }
  58. func renderUser(w http.ResponseWriter, r *http.Request, username, role string, status int) {
  59. user, err := dataprovider.UserExists(username, role)
  60. if err != nil {
  61. sendAPIResponse(w, r, err, "", getRespStatus(err))
  62. return
  63. }
  64. user.PrepareForRendering()
  65. if status != http.StatusOK {
  66. ctx := context.WithValue(r.Context(), render.StatusCtxKey, status)
  67. render.JSON(w, r.WithContext(ctx), user)
  68. } else {
  69. render.JSON(w, r, user)
  70. }
  71. }
  72. func addUser(w http.ResponseWriter, r *http.Request) {
  73. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  74. claims, err := getTokenClaims(r)
  75. if err != nil || claims.Username == "" {
  76. sendAPIResponse(w, r, err, "Invalid token claims", http.StatusBadRequest)
  77. return
  78. }
  79. admin, err := dataprovider.AdminExists(claims.Username)
  80. if err != nil {
  81. sendAPIResponse(w, r, err, "", getRespStatus(err))
  82. return
  83. }
  84. var user dataprovider.User
  85. if admin.Filters.Preferences.DefaultUsersExpiration > 0 {
  86. user.ExpirationDate = util.GetTimeAsMsSinceEpoch(time.Now().Add(24 * time.Hour * time.Duration(admin.Filters.Preferences.DefaultUsersExpiration)))
  87. }
  88. err = render.DecodeJSON(r.Body, &user)
  89. if err != nil {
  90. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  91. return
  92. }
  93. if claims.Role != "" {
  94. user.Role = claims.Role
  95. }
  96. user.LastPasswordChange = 0
  97. user.Filters.RecoveryCodes = nil
  98. user.Filters.TOTPConfig = dataprovider.UserTOTPConfig{
  99. Enabled: false,
  100. }
  101. err = dataprovider.AddUser(&user, claims.Username, util.GetIPFromRemoteAddress(r.RemoteAddr), claims.Role)
  102. if err != nil {
  103. sendAPIResponse(w, r, err, "", getRespStatus(err))
  104. return
  105. }
  106. renderUser(w, r, user.Username, claims.Role, http.StatusCreated)
  107. }
  108. func disableUser2FA(w http.ResponseWriter, r *http.Request) {
  109. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  110. claims, err := getTokenClaims(r)
  111. if err != nil || claims.Username == "" {
  112. sendAPIResponse(w, r, err, "Invalid token claims", http.StatusBadRequest)
  113. return
  114. }
  115. username := getURLParam(r, "username")
  116. user, err := dataprovider.UserExists(username, claims.Role)
  117. if err != nil {
  118. sendAPIResponse(w, r, err, "", getRespStatus(err))
  119. return
  120. }
  121. user.Filters.RecoveryCodes = nil
  122. user.Filters.TOTPConfig = dataprovider.UserTOTPConfig{
  123. Enabled: false,
  124. }
  125. if err := dataprovider.UpdateUser(&user, claims.Username, util.GetIPFromRemoteAddress(r.RemoteAddr), claims.Role); err != nil {
  126. sendAPIResponse(w, r, err, "", getRespStatus(err))
  127. return
  128. }
  129. sendAPIResponse(w, r, nil, "2FA disabled", http.StatusOK)
  130. }
  131. func updateUser(w http.ResponseWriter, r *http.Request) {
  132. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  133. claims, err := getTokenClaims(r)
  134. if err != nil || claims.Username == "" {
  135. sendAPIResponse(w, r, err, "Invalid token claims", http.StatusBadRequest)
  136. return
  137. }
  138. username := getURLParam(r, "username")
  139. disconnect := 0
  140. if _, ok := r.URL.Query()["disconnect"]; ok {
  141. disconnect, err = strconv.Atoi(r.URL.Query().Get("disconnect"))
  142. if err != nil {
  143. err = fmt.Errorf("invalid disconnect parameter: %v", err)
  144. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  145. return
  146. }
  147. }
  148. user, err := dataprovider.UserExists(username, claims.Role)
  149. if err != nil {
  150. sendAPIResponse(w, r, err, "", getRespStatus(err))
  151. return
  152. }
  153. var updatedUser dataprovider.User
  154. updatedUser.Password = user.Password
  155. err = render.DecodeJSON(r.Body, &updatedUser)
  156. if err != nil {
  157. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  158. return
  159. }
  160. updatedUser.ID = user.ID
  161. updatedUser.Username = user.Username
  162. updatedUser.Filters.RecoveryCodes = user.Filters.RecoveryCodes
  163. updatedUser.Filters.TOTPConfig = user.Filters.TOTPConfig
  164. updatedUser.LastPasswordChange = user.LastPasswordChange
  165. updatedUser.SetEmptySecretsIfNil()
  166. updateEncryptedSecrets(&updatedUser.FsConfig, user.FsConfig.S3Config.AccessSecret, user.FsConfig.AzBlobConfig.AccountKey,
  167. user.FsConfig.AzBlobConfig.SASURL, user.FsConfig.GCSConfig.Credentials, user.FsConfig.CryptConfig.Passphrase,
  168. user.FsConfig.SFTPConfig.Password, user.FsConfig.SFTPConfig.PrivateKey, user.FsConfig.SFTPConfig.KeyPassphrase,
  169. user.FsConfig.HTTPConfig.Password, user.FsConfig.HTTPConfig.APIKey)
  170. if claims.Role != "" {
  171. updatedUser.Role = claims.Role
  172. }
  173. err = dataprovider.UpdateUser(&updatedUser, claims.Username, util.GetIPFromRemoteAddress(r.RemoteAddr), claims.Role)
  174. if err != nil {
  175. sendAPIResponse(w, r, err, "", getRespStatus(err))
  176. return
  177. }
  178. sendAPIResponse(w, r, err, "User updated", http.StatusOK)
  179. if disconnect == 1 {
  180. disconnectUser(user.Username)
  181. }
  182. }
  183. func deleteUser(w http.ResponseWriter, r *http.Request) {
  184. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  185. claims, err := getTokenClaims(r)
  186. if err != nil || claims.Username == "" {
  187. sendAPIResponse(w, r, err, "Invalid token claims", http.StatusBadRequest)
  188. return
  189. }
  190. username := getURLParam(r, "username")
  191. err = dataprovider.DeleteUser(username, claims.Username, util.GetIPFromRemoteAddress(r.RemoteAddr), claims.Role)
  192. if err != nil {
  193. sendAPIResponse(w, r, err, "", getRespStatus(err))
  194. return
  195. }
  196. sendAPIResponse(w, r, err, "User deleted", http.StatusOK)
  197. disconnectUser(dataprovider.ConvertName(username))
  198. }
  199. func forgotUserPassword(w http.ResponseWriter, r *http.Request) {
  200. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  201. if !smtp.IsEnabled() {
  202. sendAPIResponse(w, r, nil, "No SMTP configuration", http.StatusBadRequest)
  203. return
  204. }
  205. err := handleForgotPassword(r, getURLParam(r, "username"), false)
  206. if err != nil {
  207. sendAPIResponse(w, r, err, "", getRespStatus(err))
  208. return
  209. }
  210. sendAPIResponse(w, r, err, "Check your email for the confirmation code", http.StatusOK)
  211. }
  212. func resetUserPassword(w http.ResponseWriter, r *http.Request) {
  213. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  214. var req pwdReset
  215. err := render.DecodeJSON(r.Body, &req)
  216. if err != nil {
  217. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  218. return
  219. }
  220. _, _, err = handleResetPassword(r, req.Code, req.Password, false)
  221. if err != nil {
  222. sendAPIResponse(w, r, err, "", getRespStatus(err))
  223. return
  224. }
  225. sendAPIResponse(w, r, err, "Password reset successful", http.StatusOK)
  226. }
  227. func disconnectUser(username string) {
  228. for _, stat := range common.Connections.GetStats("") {
  229. if stat.Username == username {
  230. common.Connections.Close(stat.ConnectionID, "")
  231. }
  232. }
  233. }
  234. func updateEncryptedSecrets(fsConfig *vfs.Filesystem, currentS3AccessSecret, currentAzAccountKey, currentAzSASUrl,
  235. currentGCSCredentials, currentCryptoPassphrase, currentSFTPPassword, currentSFTPKey, currentSFTPKeyPassphrase,
  236. currentHTTPPassword, currentHTTPAPIKey *kms.Secret) {
  237. // we use the new access secret if plain or empty, otherwise the old value
  238. switch fsConfig.Provider {
  239. case sdk.S3FilesystemProvider:
  240. if fsConfig.S3Config.AccessSecret.IsNotPlainAndNotEmpty() {
  241. fsConfig.S3Config.AccessSecret = currentS3AccessSecret
  242. }
  243. case sdk.AzureBlobFilesystemProvider:
  244. if fsConfig.AzBlobConfig.AccountKey.IsNotPlainAndNotEmpty() {
  245. fsConfig.AzBlobConfig.AccountKey = currentAzAccountKey
  246. }
  247. if fsConfig.AzBlobConfig.SASURL.IsNotPlainAndNotEmpty() {
  248. fsConfig.AzBlobConfig.SASURL = currentAzSASUrl
  249. }
  250. case sdk.GCSFilesystemProvider:
  251. // for GCS credentials will be cleared if we enable automatic credentials
  252. // so keep the old credentials here if no new credentials are provided
  253. if !fsConfig.GCSConfig.Credentials.IsPlain() {
  254. fsConfig.GCSConfig.Credentials = currentGCSCredentials
  255. }
  256. case sdk.CryptedFilesystemProvider:
  257. if fsConfig.CryptConfig.Passphrase.IsNotPlainAndNotEmpty() {
  258. fsConfig.CryptConfig.Passphrase = currentCryptoPassphrase
  259. }
  260. case sdk.SFTPFilesystemProvider:
  261. updateSFTPFsEncryptedSecrets(fsConfig, currentSFTPPassword, currentSFTPKey, currentSFTPKeyPassphrase)
  262. case sdk.HTTPFilesystemProvider:
  263. updateHTTPFsEncryptedSecrets(fsConfig, currentHTTPPassword, currentHTTPAPIKey)
  264. }
  265. }
  266. func updateSFTPFsEncryptedSecrets(fsConfig *vfs.Filesystem, currentSFTPPassword, currentSFTPKey,
  267. currentSFTPKeyPassphrase *kms.Secret,
  268. ) {
  269. if fsConfig.SFTPConfig.Password.IsNotPlainAndNotEmpty() {
  270. fsConfig.SFTPConfig.Password = currentSFTPPassword
  271. }
  272. if fsConfig.SFTPConfig.PrivateKey.IsNotPlainAndNotEmpty() {
  273. fsConfig.SFTPConfig.PrivateKey = currentSFTPKey
  274. }
  275. if fsConfig.SFTPConfig.KeyPassphrase.IsNotPlainAndNotEmpty() {
  276. fsConfig.SFTPConfig.KeyPassphrase = currentSFTPKeyPassphrase
  277. }
  278. }
  279. func updateHTTPFsEncryptedSecrets(fsConfig *vfs.Filesystem, currentHTTPPassword, currentHTTPAPIKey *kms.Secret) {
  280. if fsConfig.HTTPConfig.Password.IsNotPlainAndNotEmpty() {
  281. fsConfig.HTTPConfig.Password = currentHTTPPassword
  282. }
  283. if fsConfig.HTTPConfig.APIKey.IsNotPlainAndNotEmpty() {
  284. fsConfig.HTTPConfig.APIKey = currentHTTPAPIKey
  285. }
  286. }