api_user.go 11 KB

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