api_user.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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. "github.com/go-chi/render"
  21. "github.com/sftpgo/sdk"
  22. "github.com/drakkan/sftpgo/v2/internal/common"
  23. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  24. "github.com/drakkan/sftpgo/v2/internal/kms"
  25. "github.com/drakkan/sftpgo/v2/internal/logger"
  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. users, err := dataprovider.GetUsers(limit, offset, order)
  37. if err == nil {
  38. render.JSON(w, r, users)
  39. } else {
  40. sendAPIResponse(w, r, err, "", http.StatusInternalServerError)
  41. }
  42. }
  43. func getUserByUsername(w http.ResponseWriter, r *http.Request) {
  44. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  45. username := getURLParam(r, "username")
  46. renderUser(w, r, username, http.StatusOK)
  47. }
  48. func renderUser(w http.ResponseWriter, r *http.Request, username string, status int) {
  49. user, err := dataprovider.UserExists(username)
  50. if err != nil {
  51. sendAPIResponse(w, r, err, "", getRespStatus(err))
  52. return
  53. }
  54. user.PrepareForRendering()
  55. if status != http.StatusOK {
  56. ctx := context.WithValue(r.Context(), render.StatusCtxKey, status)
  57. render.JSON(w, r.WithContext(ctx), user)
  58. } else {
  59. render.JSON(w, r, user)
  60. }
  61. }
  62. func addUser(w http.ResponseWriter, r *http.Request) {
  63. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  64. claims, err := getTokenClaims(r)
  65. if err != nil || claims.Username == "" {
  66. sendAPIResponse(w, r, err, "Invalid token claims", http.StatusBadRequest)
  67. return
  68. }
  69. var user dataprovider.User
  70. err = render.DecodeJSON(r.Body, &user)
  71. if err != nil {
  72. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  73. return
  74. }
  75. user.Filters.RecoveryCodes = nil
  76. user.Filters.TOTPConfig = dataprovider.UserTOTPConfig{
  77. Enabled: false,
  78. }
  79. err = dataprovider.AddUser(&user, claims.Username, util.GetIPFromRemoteAddress(r.RemoteAddr))
  80. if err != nil {
  81. sendAPIResponse(w, r, err, "", getRespStatus(err))
  82. return
  83. }
  84. renderUser(w, r, user.Username, http.StatusCreated)
  85. }
  86. func disableUser2FA(w http.ResponseWriter, r *http.Request) {
  87. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  88. claims, err := getTokenClaims(r)
  89. if err != nil || claims.Username == "" {
  90. sendAPIResponse(w, r, err, "Invalid token claims", http.StatusBadRequest)
  91. return
  92. }
  93. username := getURLParam(r, "username")
  94. user, err := dataprovider.UserExists(username)
  95. if err != nil {
  96. sendAPIResponse(w, r, err, "", getRespStatus(err))
  97. return
  98. }
  99. user.Filters.RecoveryCodes = nil
  100. user.Filters.TOTPConfig = dataprovider.UserTOTPConfig{
  101. Enabled: false,
  102. }
  103. if err := dataprovider.UpdateUser(&user, claims.Username, util.GetIPFromRemoteAddress(r.RemoteAddr)); err != nil {
  104. sendAPIResponse(w, r, err, "", getRespStatus(err))
  105. return
  106. }
  107. sendAPIResponse(w, r, nil, "2FA disabled", http.StatusOK)
  108. }
  109. func updateUser(w http.ResponseWriter, r *http.Request) {
  110. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  111. claims, err := getTokenClaims(r)
  112. if err != nil || claims.Username == "" {
  113. sendAPIResponse(w, r, err, "Invalid token claims", http.StatusBadRequest)
  114. return
  115. }
  116. username := getURLParam(r, "username")
  117. disconnect := 0
  118. if _, ok := r.URL.Query()["disconnect"]; ok {
  119. disconnect, err = strconv.Atoi(r.URL.Query().Get("disconnect"))
  120. if err != nil {
  121. err = fmt.Errorf("invalid disconnect parameter: %v", err)
  122. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  123. return
  124. }
  125. }
  126. user, err := dataprovider.UserExists(username)
  127. if err != nil {
  128. sendAPIResponse(w, r, err, "", getRespStatus(err))
  129. return
  130. }
  131. userID := user.ID
  132. username = user.Username
  133. totpConfig := user.Filters.TOTPConfig
  134. recoveryCodes := user.Filters.RecoveryCodes
  135. currentPermissions := user.Permissions
  136. currentS3AccessSecret := user.FsConfig.S3Config.AccessSecret
  137. currentAzAccountKey := user.FsConfig.AzBlobConfig.AccountKey
  138. currentAzSASUrl := user.FsConfig.AzBlobConfig.SASURL
  139. currentGCSCredentials := user.FsConfig.GCSConfig.Credentials
  140. currentCryptoPassphrase := user.FsConfig.CryptConfig.Passphrase
  141. currentSFTPPassword := user.FsConfig.SFTPConfig.Password
  142. currentSFTPKey := user.FsConfig.SFTPConfig.PrivateKey
  143. currentSFTPKeyPassphrase := user.FsConfig.SFTPConfig.KeyPassphrase
  144. currentHTTPPassword := user.FsConfig.HTTPConfig.Password
  145. currentHTTPAPIKey := user.FsConfig.HTTPConfig.APIKey
  146. user.Permissions = make(map[string][]string)
  147. user.FsConfig.S3Config = vfs.S3FsConfig{}
  148. user.FsConfig.AzBlobConfig = vfs.AzBlobFsConfig{}
  149. user.FsConfig.GCSConfig = vfs.GCSFsConfig{}
  150. user.FsConfig.CryptConfig = vfs.CryptFsConfig{}
  151. user.FsConfig.SFTPConfig = vfs.SFTPFsConfig{}
  152. user.FsConfig.HTTPConfig = vfs.HTTPFsConfig{}
  153. user.Filters.TOTPConfig = dataprovider.UserTOTPConfig{}
  154. user.Filters.RecoveryCodes = nil
  155. user.VirtualFolders = nil
  156. err = render.DecodeJSON(r.Body, &user)
  157. if err != nil {
  158. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  159. return
  160. }
  161. user.ID = userID
  162. user.Username = username
  163. user.Filters.TOTPConfig = totpConfig
  164. user.Filters.RecoveryCodes = recoveryCodes
  165. user.SetEmptySecretsIfNil()
  166. // we use new Permissions if passed otherwise the old ones
  167. if len(user.Permissions) == 0 {
  168. user.Permissions = currentPermissions
  169. }
  170. updateEncryptedSecrets(&user.FsConfig, currentS3AccessSecret, currentAzAccountKey, currentAzSASUrl,
  171. currentGCSCredentials, currentCryptoPassphrase, currentSFTPPassword, currentSFTPKey, currentSFTPKeyPassphrase,
  172. currentHTTPPassword, currentHTTPAPIKey)
  173. err = dataprovider.UpdateUser(&user, claims.Username, util.GetIPFromRemoteAddress(r.RemoteAddr))
  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, claims.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))
  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), claims.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, admin string) {
  228. for _, stat := range common.Connections.GetStats() {
  229. if stat.Username == username {
  230. common.Connections.Close(stat.ConnectionID)
  231. }
  232. }
  233. for _, stat := range getNodesConnections(admin) {
  234. if stat.Username == username {
  235. n, err := dataprovider.GetNodeByName(stat.Node)
  236. if err != nil {
  237. logger.Warn(logSender, "", "unable to disconnect user %q, error getting node %q: %v", username, stat.Node, err)
  238. continue
  239. }
  240. if err := n.SendDeleteRequest(admin, fmt.Sprintf("%s/%s", activeConnectionsPath, stat.ConnectionID)); err != nil {
  241. logger.Warn(logSender, "", "unable to disconnect user %q from node %q, error: %v", username, n.Name, err)
  242. }
  243. }
  244. }
  245. }
  246. func updateEncryptedSecrets(fsConfig *vfs.Filesystem, currentS3AccessSecret, currentAzAccountKey, currentAzSASUrl,
  247. currentGCSCredentials, currentCryptoPassphrase, currentSFTPPassword, currentSFTPKey, currentSFTPKeyPassphrase,
  248. currentHTTPPassword, currentHTTPAPIKey *kms.Secret) {
  249. // we use the new access secret if plain or empty, otherwise the old value
  250. switch fsConfig.Provider {
  251. case sdk.S3FilesystemProvider:
  252. if fsConfig.S3Config.AccessSecret.IsNotPlainAndNotEmpty() {
  253. fsConfig.S3Config.AccessSecret = currentS3AccessSecret
  254. }
  255. case sdk.AzureBlobFilesystemProvider:
  256. if fsConfig.AzBlobConfig.AccountKey.IsNotPlainAndNotEmpty() {
  257. fsConfig.AzBlobConfig.AccountKey = currentAzAccountKey
  258. }
  259. if fsConfig.AzBlobConfig.SASURL.IsNotPlainAndNotEmpty() {
  260. fsConfig.AzBlobConfig.SASURL = currentAzSASUrl
  261. }
  262. case sdk.GCSFilesystemProvider:
  263. // for GCS credentials will be cleared if we enable automatic credentials
  264. // so keep the old credentials here if no new credentials are provided
  265. if !fsConfig.GCSConfig.Credentials.IsPlain() {
  266. fsConfig.GCSConfig.Credentials = currentGCSCredentials
  267. }
  268. case sdk.CryptedFilesystemProvider:
  269. if fsConfig.CryptConfig.Passphrase.IsNotPlainAndNotEmpty() {
  270. fsConfig.CryptConfig.Passphrase = currentCryptoPassphrase
  271. }
  272. case sdk.SFTPFilesystemProvider:
  273. updateSFTPFsEncryptedSecrets(fsConfig, currentSFTPPassword, currentSFTPKey, currentSFTPKeyPassphrase)
  274. case sdk.HTTPFilesystemProvider:
  275. updateHTTPFsEncryptedSecrets(fsConfig, currentHTTPPassword, currentHTTPAPIKey)
  276. }
  277. }
  278. func updateSFTPFsEncryptedSecrets(fsConfig *vfs.Filesystem, currentSFTPPassword, currentSFTPKey,
  279. currentSFTPKeyPassphrase *kms.Secret,
  280. ) {
  281. if fsConfig.SFTPConfig.Password.IsNotPlainAndNotEmpty() {
  282. fsConfig.SFTPConfig.Password = currentSFTPPassword
  283. }
  284. if fsConfig.SFTPConfig.PrivateKey.IsNotPlainAndNotEmpty() {
  285. fsConfig.SFTPConfig.PrivateKey = currentSFTPKey
  286. }
  287. if fsConfig.SFTPConfig.KeyPassphrase.IsNotPlainAndNotEmpty() {
  288. fsConfig.SFTPConfig.KeyPassphrase = currentSFTPKeyPassphrase
  289. }
  290. }
  291. func updateHTTPFsEncryptedSecrets(fsConfig *vfs.Filesystem, currentHTTPPassword, currentHTTPAPIKey *kms.Secret) {
  292. if fsConfig.HTTPConfig.Password.IsNotPlainAndNotEmpty() {
  293. fsConfig.HTTPConfig.Password = currentHTTPPassword
  294. }
  295. if fsConfig.HTTPConfig.APIKey.IsNotPlainAndNotEmpty() {
  296. fsConfig.HTTPConfig.APIKey = currentHTTPAPIKey
  297. }
  298. }