api_user.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. userID := user.ID
  154. username = user.Username
  155. lastPwdChange := user.LastPasswordChange
  156. totpConfig := user.Filters.TOTPConfig
  157. recoveryCodes := user.Filters.RecoveryCodes
  158. currentPermissions := user.Permissions
  159. currentS3AccessSecret := user.FsConfig.S3Config.AccessSecret
  160. currentAzAccountKey := user.FsConfig.AzBlobConfig.AccountKey
  161. currentAzSASUrl := user.FsConfig.AzBlobConfig.SASURL
  162. currentGCSCredentials := user.FsConfig.GCSConfig.Credentials
  163. currentCryptoPassphrase := user.FsConfig.CryptConfig.Passphrase
  164. currentSFTPPassword := user.FsConfig.SFTPConfig.Password
  165. currentSFTPKey := user.FsConfig.SFTPConfig.PrivateKey
  166. currentSFTPKeyPassphrase := user.FsConfig.SFTPConfig.KeyPassphrase
  167. currentHTTPPassword := user.FsConfig.HTTPConfig.Password
  168. currentHTTPAPIKey := user.FsConfig.HTTPConfig.APIKey
  169. user.Permissions = make(map[string][]string)
  170. user.FsConfig.S3Config = vfs.S3FsConfig{}
  171. user.FsConfig.AzBlobConfig = vfs.AzBlobFsConfig{}
  172. user.FsConfig.GCSConfig = vfs.GCSFsConfig{}
  173. user.FsConfig.CryptConfig = vfs.CryptFsConfig{}
  174. user.FsConfig.SFTPConfig = vfs.SFTPFsConfig{}
  175. user.FsConfig.HTTPConfig = vfs.HTTPFsConfig{}
  176. user.Filters.TOTPConfig = dataprovider.UserTOTPConfig{}
  177. user.Filters.RecoveryCodes = nil
  178. user.VirtualFolders = nil
  179. err = render.DecodeJSON(r.Body, &user)
  180. if err != nil {
  181. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  182. return
  183. }
  184. user.ID = userID
  185. user.Username = username
  186. user.Filters.TOTPConfig = totpConfig
  187. user.Filters.RecoveryCodes = recoveryCodes
  188. user.LastPasswordChange = lastPwdChange
  189. user.SetEmptySecretsIfNil()
  190. // we use new Permissions if passed otherwise the old ones
  191. if len(user.Permissions) == 0 {
  192. user.Permissions = currentPermissions
  193. }
  194. updateEncryptedSecrets(&user.FsConfig, currentS3AccessSecret, currentAzAccountKey, currentAzSASUrl,
  195. currentGCSCredentials, currentCryptoPassphrase, currentSFTPPassword, currentSFTPKey, currentSFTPKeyPassphrase,
  196. currentHTTPPassword, currentHTTPAPIKey)
  197. if claims.Role != "" {
  198. user.Role = claims.Role
  199. }
  200. err = dataprovider.UpdateUser(&user, claims.Username, util.GetIPFromRemoteAddress(r.RemoteAddr), claims.Role)
  201. if err != nil {
  202. sendAPIResponse(w, r, err, "", getRespStatus(err))
  203. return
  204. }
  205. sendAPIResponse(w, r, err, "User updated", http.StatusOK)
  206. if disconnect == 1 {
  207. disconnectUser(user.Username)
  208. }
  209. }
  210. func deleteUser(w http.ResponseWriter, r *http.Request) {
  211. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  212. claims, err := getTokenClaims(r)
  213. if err != nil || claims.Username == "" {
  214. sendAPIResponse(w, r, err, "Invalid token claims", http.StatusBadRequest)
  215. return
  216. }
  217. username := getURLParam(r, "username")
  218. err = dataprovider.DeleteUser(username, claims.Username, util.GetIPFromRemoteAddress(r.RemoteAddr), claims.Role)
  219. if err != nil {
  220. sendAPIResponse(w, r, err, "", getRespStatus(err))
  221. return
  222. }
  223. sendAPIResponse(w, r, err, "User deleted", http.StatusOK)
  224. disconnectUser(dataprovider.ConvertName(username))
  225. }
  226. func forgotUserPassword(w http.ResponseWriter, r *http.Request) {
  227. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  228. if !smtp.IsEnabled() {
  229. sendAPIResponse(w, r, nil, "No SMTP configuration", http.StatusBadRequest)
  230. return
  231. }
  232. err := handleForgotPassword(r, getURLParam(r, "username"), false)
  233. if err != nil {
  234. sendAPIResponse(w, r, err, "", getRespStatus(err))
  235. return
  236. }
  237. sendAPIResponse(w, r, err, "Check your email for the confirmation code", http.StatusOK)
  238. }
  239. func resetUserPassword(w http.ResponseWriter, r *http.Request) {
  240. r.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)
  241. var req pwdReset
  242. err := render.DecodeJSON(r.Body, &req)
  243. if err != nil {
  244. sendAPIResponse(w, r, err, "", http.StatusBadRequest)
  245. return
  246. }
  247. _, _, err = handleResetPassword(r, req.Code, req.Password, false)
  248. if err != nil {
  249. sendAPIResponse(w, r, err, "", getRespStatus(err))
  250. return
  251. }
  252. sendAPIResponse(w, r, err, "Password reset successful", http.StatusOK)
  253. }
  254. func disconnectUser(username string) {
  255. for _, stat := range common.Connections.GetStats("") {
  256. if stat.Username == username {
  257. common.Connections.Close(stat.ConnectionID, "")
  258. }
  259. }
  260. }
  261. func updateEncryptedSecrets(fsConfig *vfs.Filesystem, currentS3AccessSecret, currentAzAccountKey, currentAzSASUrl,
  262. currentGCSCredentials, currentCryptoPassphrase, currentSFTPPassword, currentSFTPKey, currentSFTPKeyPassphrase,
  263. currentHTTPPassword, currentHTTPAPIKey *kms.Secret) {
  264. // we use the new access secret if plain or empty, otherwise the old value
  265. switch fsConfig.Provider {
  266. case sdk.S3FilesystemProvider:
  267. if fsConfig.S3Config.AccessSecret.IsNotPlainAndNotEmpty() {
  268. fsConfig.S3Config.AccessSecret = currentS3AccessSecret
  269. }
  270. case sdk.AzureBlobFilesystemProvider:
  271. if fsConfig.AzBlobConfig.AccountKey.IsNotPlainAndNotEmpty() {
  272. fsConfig.AzBlobConfig.AccountKey = currentAzAccountKey
  273. }
  274. if fsConfig.AzBlobConfig.SASURL.IsNotPlainAndNotEmpty() {
  275. fsConfig.AzBlobConfig.SASURL = currentAzSASUrl
  276. }
  277. case sdk.GCSFilesystemProvider:
  278. // for GCS credentials will be cleared if we enable automatic credentials
  279. // so keep the old credentials here if no new credentials are provided
  280. if !fsConfig.GCSConfig.Credentials.IsPlain() {
  281. fsConfig.GCSConfig.Credentials = currentGCSCredentials
  282. }
  283. case sdk.CryptedFilesystemProvider:
  284. if fsConfig.CryptConfig.Passphrase.IsNotPlainAndNotEmpty() {
  285. fsConfig.CryptConfig.Passphrase = currentCryptoPassphrase
  286. }
  287. case sdk.SFTPFilesystemProvider:
  288. updateSFTPFsEncryptedSecrets(fsConfig, currentSFTPPassword, currentSFTPKey, currentSFTPKeyPassphrase)
  289. case sdk.HTTPFilesystemProvider:
  290. updateHTTPFsEncryptedSecrets(fsConfig, currentHTTPPassword, currentHTTPAPIKey)
  291. }
  292. }
  293. func updateSFTPFsEncryptedSecrets(fsConfig *vfs.Filesystem, currentSFTPPassword, currentSFTPKey,
  294. currentSFTPKeyPassphrase *kms.Secret,
  295. ) {
  296. if fsConfig.SFTPConfig.Password.IsNotPlainAndNotEmpty() {
  297. fsConfig.SFTPConfig.Password = currentSFTPPassword
  298. }
  299. if fsConfig.SFTPConfig.PrivateKey.IsNotPlainAndNotEmpty() {
  300. fsConfig.SFTPConfig.PrivateKey = currentSFTPKey
  301. }
  302. if fsConfig.SFTPConfig.KeyPassphrase.IsNotPlainAndNotEmpty() {
  303. fsConfig.SFTPConfig.KeyPassphrase = currentSFTPKeyPassphrase
  304. }
  305. }
  306. func updateHTTPFsEncryptedSecrets(fsConfig *vfs.Filesystem, currentHTTPPassword, currentHTTPAPIKey *kms.Secret) {
  307. if fsConfig.HTTPConfig.Password.IsNotPlainAndNotEmpty() {
  308. fsConfig.HTTPConfig.Password = currentHTTPPassword
  309. }
  310. if fsConfig.HTTPConfig.APIKey.IsNotPlainAndNotEmpty() {
  311. fsConfig.HTTPConfig.APIKey = currentHTTPAPIKey
  312. }
  313. }