user.go 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846
  1. // Copyright (C) 2019 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 dataprovider
  15. import (
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "math"
  20. "net"
  21. "os"
  22. "path"
  23. "slices"
  24. "strconv"
  25. "strings"
  26. "time"
  27. "github.com/rs/xid"
  28. "github.com/sftpgo/sdk"
  29. "github.com/drakkan/sftpgo/v2/internal/kms"
  30. "github.com/drakkan/sftpgo/v2/internal/logger"
  31. "github.com/drakkan/sftpgo/v2/internal/mfa"
  32. "github.com/drakkan/sftpgo/v2/internal/plugin"
  33. "github.com/drakkan/sftpgo/v2/internal/util"
  34. "github.com/drakkan/sftpgo/v2/internal/vfs"
  35. )
  36. // Available permissions for SFTPGo users
  37. const (
  38. // All permissions are granted
  39. PermAny = "*"
  40. // List items such as files and directories is allowed
  41. PermListItems = "list"
  42. // download files is allowed
  43. PermDownload = "download"
  44. // upload files is allowed
  45. PermUpload = "upload"
  46. // overwrite an existing file, while uploading, is allowed
  47. // upload permission is required to allow file overwrite
  48. PermOverwrite = "overwrite"
  49. // delete files or directories is allowed
  50. PermDelete = "delete"
  51. // delete files is allowed
  52. PermDeleteFiles = "delete_files"
  53. // delete directories is allowed
  54. PermDeleteDirs = "delete_dirs"
  55. // rename files or directories is allowed
  56. PermRename = "rename"
  57. // rename files is allowed
  58. PermRenameFiles = "rename_files"
  59. // rename directories is allowed
  60. PermRenameDirs = "rename_dirs"
  61. // create directories is allowed
  62. PermCreateDirs = "create_dirs"
  63. // create symbolic links is allowed
  64. PermCreateSymlinks = "create_symlinks"
  65. // changing file or directory permissions is allowed
  66. PermChmod = "chmod"
  67. // changing file or directory owner and group is allowed
  68. PermChown = "chown"
  69. // changing file or directory access and modification time is allowed
  70. PermChtimes = "chtimes"
  71. // copying files or directories is allowed
  72. PermCopy = "copy"
  73. )
  74. // Available login methods
  75. const (
  76. LoginMethodNoAuthTried = "no_auth_tried"
  77. LoginMethodPassword = "password"
  78. SSHLoginMethodPassword = "password-over-SSH"
  79. SSHLoginMethodPublicKey = "publickey"
  80. SSHLoginMethodKeyboardInteractive = "keyboard-interactive"
  81. SSHLoginMethodKeyAndPassword = "publickey+password"
  82. SSHLoginMethodKeyAndKeyboardInt = "publickey+keyboard-interactive"
  83. LoginMethodTLSCertificate = "TLSCertificate"
  84. LoginMethodTLSCertificateAndPwd = "TLSCertificate+password"
  85. LoginMethodIDP = "IDP"
  86. )
  87. var (
  88. errNoMatchingVirtualFolder = errors.New("no matching virtual folder found")
  89. permsRenameAny = []string{PermRename, PermRenameDirs, PermRenameFiles}
  90. permsDeleteAny = []string{PermDelete, PermDeleteDirs, PermDeleteFiles}
  91. )
  92. // RecoveryCode defines a 2FA recovery code
  93. type RecoveryCode struct {
  94. Secret *kms.Secret `json:"secret"`
  95. Used bool `json:"used,omitempty"`
  96. }
  97. // UserTOTPConfig defines the time-based one time password configuration
  98. type UserTOTPConfig struct {
  99. Enabled bool `json:"enabled,omitempty"`
  100. ConfigName string `json:"config_name,omitempty"`
  101. Secret *kms.Secret `json:"secret,omitempty"`
  102. // TOTP will be required for the specified protocols.
  103. // SSH protocol (SFTP/SCP/SSH commands) will ask for the TOTP passcode if the client uses keyboard interactive
  104. // authentication.
  105. // FTP have no standard way to support two factor authentication, if you
  106. // enable the support for this protocol you have to add the TOTP passcode after the password.
  107. // For example if your password is "password" and your one time passcode is
  108. // "123456" you have to use "password123456" as password.
  109. Protocols []string `json:"protocols,omitempty"`
  110. }
  111. // UserFilters defines additional restrictions for a user
  112. // TODO: rename to UserOptions in v3
  113. type UserFilters struct {
  114. sdk.BaseUserFilters
  115. // User must change password from WebClient/REST API at next login.
  116. RequirePasswordChange bool `json:"require_password_change,omitempty"`
  117. // Time-based one time passwords configuration
  118. TOTPConfig UserTOTPConfig `json:"totp_config,omitempty"`
  119. // Recovery codes to use if the user loses access to their second factor auth device.
  120. // Each code can only be used once, you should use these codes to login and disable or
  121. // reset 2FA for your account
  122. RecoveryCodes []RecoveryCode `json:"recovery_codes,omitempty"`
  123. }
  124. // User defines a SFTPGo user
  125. type User struct {
  126. sdk.BaseUser
  127. // Additional restrictions
  128. Filters UserFilters `json:"filters"`
  129. // Mapping between virtual paths and virtual folders
  130. VirtualFolders []vfs.VirtualFolder `json:"virtual_folders,omitempty"`
  131. // Filesystem configuration details
  132. FsConfig vfs.Filesystem `json:"filesystem"`
  133. // groups associated with this user
  134. Groups []sdk.GroupMapping `json:"groups,omitempty"`
  135. // we store the filesystem here using the base path as key.
  136. fsCache map[string]vfs.Fs `json:"-"`
  137. // true if group settings are already applied for this user
  138. groupSettingsApplied bool `json:"-"`
  139. // in multi node setups we mark the user as deleted to be able to update the webdav cache
  140. DeletedAt int64 `json:"-"`
  141. }
  142. // GetFilesystem returns the base filesystem for this user
  143. func (u *User) GetFilesystem(connectionID string) (fs vfs.Fs, err error) {
  144. return u.GetFilesystemForPath("/", connectionID)
  145. }
  146. func (u *User) getRootFs(connectionID string) (fs vfs.Fs, err error) {
  147. switch u.FsConfig.Provider {
  148. case sdk.S3FilesystemProvider:
  149. return vfs.NewS3Fs(connectionID, u.GetHomeDir(), "", u.FsConfig.S3Config)
  150. case sdk.GCSFilesystemProvider:
  151. return vfs.NewGCSFs(connectionID, u.GetHomeDir(), "", u.FsConfig.GCSConfig)
  152. case sdk.AzureBlobFilesystemProvider:
  153. return vfs.NewAzBlobFs(connectionID, u.GetHomeDir(), "", u.FsConfig.AzBlobConfig)
  154. case sdk.CryptedFilesystemProvider:
  155. return vfs.NewCryptFs(connectionID, u.GetHomeDir(), "", u.FsConfig.CryptConfig)
  156. case sdk.SFTPFilesystemProvider:
  157. forbiddenSelfUsers, err := u.getForbiddenSFTPSelfUsers(u.FsConfig.SFTPConfig.Username)
  158. if err != nil {
  159. return nil, err
  160. }
  161. forbiddenSelfUsers = append(forbiddenSelfUsers, u.Username)
  162. return vfs.NewSFTPFs(connectionID, "", u.GetHomeDir(), forbiddenSelfUsers, u.FsConfig.SFTPConfig)
  163. case sdk.HTTPFilesystemProvider:
  164. return vfs.NewHTTPFs(connectionID, u.GetHomeDir(), "", u.FsConfig.HTTPConfig)
  165. default:
  166. return vfs.NewOsFs(connectionID, u.GetHomeDir(), "", &u.FsConfig.OSConfig), nil
  167. }
  168. }
  169. func (u *User) checkDirWithParents(virtualDirPath, connectionID string) error {
  170. dirs := util.GetDirsForVirtualPath(virtualDirPath)
  171. for idx := len(dirs) - 1; idx >= 0; idx-- {
  172. vPath := dirs[idx]
  173. if vPath == "/" {
  174. continue
  175. }
  176. fs, err := u.GetFilesystemForPath(vPath, connectionID)
  177. if err != nil {
  178. return fmt.Errorf("unable to get fs for path %q: %w", vPath, err)
  179. }
  180. if fs.HasVirtualFolders() {
  181. continue
  182. }
  183. fsPath, err := fs.ResolvePath(vPath)
  184. if err != nil {
  185. return fmt.Errorf("unable to resolve path %q: %w", vPath, err)
  186. }
  187. _, err = fs.Stat(fsPath)
  188. if err == nil {
  189. continue
  190. }
  191. if fs.IsNotExist(err) {
  192. err = fs.Mkdir(fsPath)
  193. if err != nil {
  194. return err
  195. }
  196. vfs.SetPathPermissions(fs, fsPath, u.GetUID(), u.GetGID())
  197. } else {
  198. return fmt.Errorf("unable to stat path %q: %w", vPath, err)
  199. }
  200. }
  201. return nil
  202. }
  203. func (u *User) checkLocalHomeDir(connectionID string) {
  204. switch u.FsConfig.Provider {
  205. case sdk.LocalFilesystemProvider, sdk.CryptedFilesystemProvider:
  206. return
  207. default:
  208. osFs := vfs.NewOsFs(connectionID, u.GetHomeDir(), "", nil)
  209. osFs.CheckRootPath(u.Username, u.GetUID(), u.GetGID())
  210. }
  211. }
  212. func (u *User) checkRootPath(connectionID string) error {
  213. fs, err := u.GetFilesystemForPath("/", connectionID)
  214. if err != nil {
  215. logger.Warn(logSender, connectionID, "could not create main filesystem for user %q err: %v", u.Username, err)
  216. return fmt.Errorf("could not create root filesystem: %w", err)
  217. }
  218. fs.CheckRootPath(u.Username, u.GetUID(), u.GetGID())
  219. return nil
  220. }
  221. // CheckFsRoot check the root directory for the main fs and the virtual folders.
  222. // It returns an error if the main filesystem cannot be created
  223. func (u *User) CheckFsRoot(connectionID string) error {
  224. if u.Filters.DisableFsChecks {
  225. return nil
  226. }
  227. delay := lastLoginMinDelay
  228. if u.Filters.ExternalAuthCacheTime > 0 {
  229. cacheTime := time.Duration(u.Filters.ExternalAuthCacheTime) * time.Second
  230. if cacheTime > delay {
  231. delay = cacheTime
  232. }
  233. }
  234. if isLastActivityRecent(u.LastLogin, delay) {
  235. if u.LastLogin > u.UpdatedAt {
  236. if config.IsShared == 1 {
  237. u.checkLocalHomeDir(connectionID)
  238. }
  239. return nil
  240. }
  241. }
  242. err := u.checkRootPath(connectionID)
  243. if err != nil {
  244. return err
  245. }
  246. if u.Filters.StartDirectory != "" {
  247. err = u.checkDirWithParents(u.Filters.StartDirectory, connectionID)
  248. if err != nil {
  249. logger.Warn(logSender, connectionID, "could not create start directory %q, err: %v",
  250. u.Filters.StartDirectory, err)
  251. }
  252. }
  253. for idx := range u.VirtualFolders {
  254. v := &u.VirtualFolders[idx]
  255. fs, err := u.GetFilesystemForPath(v.VirtualPath, connectionID)
  256. if err == nil {
  257. fs.CheckRootPath(u.Username, u.GetUID(), u.GetGID())
  258. }
  259. // now check intermediary folders
  260. err = u.checkDirWithParents(path.Dir(v.VirtualPath), connectionID)
  261. if err != nil {
  262. logger.Warn(logSender, connectionID, "could not create intermediary dir to %q, err: %v", v.VirtualPath, err)
  263. }
  264. }
  265. return nil
  266. }
  267. // GetCleanedPath returns a clean POSIX absolute path using the user start directory as base
  268. // if the provided rawVirtualPath is relative
  269. func (u *User) GetCleanedPath(rawVirtualPath string) string {
  270. if u.Filters.StartDirectory != "" {
  271. if !path.IsAbs(rawVirtualPath) {
  272. var b strings.Builder
  273. b.Grow(len(u.Filters.StartDirectory) + 1 + len(rawVirtualPath))
  274. b.WriteString(u.Filters.StartDirectory)
  275. b.WriteString("/")
  276. b.WriteString(rawVirtualPath)
  277. return util.CleanPath(b.String())
  278. }
  279. }
  280. return util.CleanPath(rawVirtualPath)
  281. }
  282. // isFsEqual returns true if the filesystem configurations are the same
  283. func (u *User) isFsEqual(other *User) bool {
  284. if u.FsConfig.Provider == sdk.LocalFilesystemProvider && u.GetHomeDir() != other.GetHomeDir() {
  285. return false
  286. }
  287. if !u.FsConfig.IsEqual(other.FsConfig) {
  288. return false
  289. }
  290. if u.Filters.StartDirectory != other.Filters.StartDirectory {
  291. return false
  292. }
  293. if len(u.VirtualFolders) != len(other.VirtualFolders) {
  294. return false
  295. }
  296. for idx := range u.VirtualFolders {
  297. f := &u.VirtualFolders[idx]
  298. found := false
  299. for idx1 := range other.VirtualFolders {
  300. f1 := &other.VirtualFolders[idx1]
  301. if f.VirtualPath == f1.VirtualPath {
  302. found = true
  303. if f.FsConfig.Provider == sdk.LocalFilesystemProvider && f.MappedPath != f1.MappedPath {
  304. return false
  305. }
  306. if !f.FsConfig.IsEqual(f1.FsConfig) {
  307. return false
  308. }
  309. }
  310. }
  311. if !found {
  312. return false
  313. }
  314. }
  315. return true
  316. }
  317. func (u *User) isTimeBasedAccessAllowed(when time.Time) bool {
  318. if len(u.Filters.AccessTime) == 0 {
  319. return true
  320. }
  321. if when.IsZero() {
  322. when = time.Now()
  323. }
  324. if UseLocalTime() {
  325. when = when.Local()
  326. } else {
  327. when = when.UTC()
  328. }
  329. weekDay := when.Weekday()
  330. hhMM := when.Format("15:04")
  331. for _, p := range u.Filters.AccessTime {
  332. if p.DayOfWeek == int(weekDay) {
  333. if hhMM >= p.From && hhMM <= p.To {
  334. return true
  335. }
  336. }
  337. }
  338. return false
  339. }
  340. // CheckLoginConditions checks user access restrictions
  341. func (u *User) CheckLoginConditions() error {
  342. if u.Status < 1 {
  343. return fmt.Errorf("user %q is disabled", u.Username)
  344. }
  345. if u.ExpirationDate > 0 && u.ExpirationDate < util.GetTimeAsMsSinceEpoch(time.Now()) {
  346. return fmt.Errorf("user %q is expired, expiration timestamp: %v current timestamp: %v", u.Username,
  347. u.ExpirationDate, util.GetTimeAsMsSinceEpoch(time.Now()))
  348. }
  349. if u.isTimeBasedAccessAllowed(time.Now()) {
  350. return nil
  351. }
  352. return errors.New("access is not allowed at this time")
  353. }
  354. // hideConfidentialData hides user confidential data
  355. func (u *User) hideConfidentialData() {
  356. u.Password = ""
  357. u.FsConfig.HideConfidentialData()
  358. if u.Filters.TOTPConfig.Secret != nil {
  359. u.Filters.TOTPConfig.Secret.Hide()
  360. }
  361. for _, code := range u.Filters.RecoveryCodes {
  362. if code.Secret != nil {
  363. code.Secret.Hide()
  364. }
  365. }
  366. }
  367. // CheckMaxShareExpiration returns an error if the share expiration exceed the
  368. // maximum allowed date.
  369. func (u *User) CheckMaxShareExpiration(expiresAt time.Time) error {
  370. if u.Filters.MaxSharesExpiration == 0 {
  371. return nil
  372. }
  373. maxAllowedExpiration := time.Now().Add(24 * time.Hour * time.Duration(u.Filters.MaxSharesExpiration+1))
  374. maxAllowedExpiration = time.Date(maxAllowedExpiration.Year(), maxAllowedExpiration.Month(),
  375. maxAllowedExpiration.Day(), 0, 0, 0, 0, maxAllowedExpiration.Location())
  376. if util.GetTimeAsMsSinceEpoch(expiresAt) == 0 || expiresAt.After(maxAllowedExpiration) {
  377. return util.NewValidationError(fmt.Sprintf("the share must expire before %s", maxAllowedExpiration.Format(time.DateOnly)))
  378. }
  379. return nil
  380. }
  381. // GetSubDirPermissions returns permissions for sub directories
  382. func (u *User) GetSubDirPermissions() []sdk.DirectoryPermissions {
  383. var result []sdk.DirectoryPermissions
  384. for k, v := range u.Permissions {
  385. if k == "/" {
  386. continue
  387. }
  388. dirPerms := sdk.DirectoryPermissions{
  389. Path: k,
  390. Permissions: v,
  391. }
  392. result = append(result, dirPerms)
  393. }
  394. return result
  395. }
  396. func (u *User) setAnonymousSettings() {
  397. for k := range u.Permissions {
  398. u.Permissions[k] = []string{PermListItems, PermDownload}
  399. }
  400. u.Filters.DeniedProtocols = append(u.Filters.DeniedProtocols, protocolSSH, protocolHTTP)
  401. u.Filters.DeniedProtocols = util.RemoveDuplicates(u.Filters.DeniedProtocols, false)
  402. for _, method := range ValidLoginMethods {
  403. if method != LoginMethodPassword {
  404. u.Filters.DeniedLoginMethods = append(u.Filters.DeniedLoginMethods, method)
  405. }
  406. }
  407. u.Filters.DeniedLoginMethods = util.RemoveDuplicates(u.Filters.DeniedLoginMethods, false)
  408. }
  409. // RenderAsJSON implements the renderer interface used within plugins
  410. func (u *User) RenderAsJSON(reload bool) ([]byte, error) {
  411. if reload {
  412. user, err := provider.userExists(u.Username, "")
  413. if err != nil {
  414. providerLog(logger.LevelError, "unable to reload user before rendering as json: %v", err)
  415. return nil, err
  416. }
  417. user.PrepareForRendering()
  418. return json.Marshal(user)
  419. }
  420. u.PrepareForRendering()
  421. return json.Marshal(u)
  422. }
  423. // PrepareForRendering prepares a user for rendering.
  424. // It hides confidential data and set to nil the empty secrets
  425. // so they are not serialized
  426. func (u *User) PrepareForRendering() {
  427. u.hideConfidentialData()
  428. u.FsConfig.SetNilSecretsIfEmpty()
  429. for idx := range u.VirtualFolders {
  430. folder := &u.VirtualFolders[idx]
  431. folder.PrepareForRendering()
  432. }
  433. }
  434. // HasRedactedSecret returns true if the user has a redacted secret
  435. func (u *User) hasRedactedSecret() bool {
  436. if u.FsConfig.HasRedactedSecret() {
  437. return true
  438. }
  439. for idx := range u.VirtualFolders {
  440. folder := &u.VirtualFolders[idx]
  441. if folder.HasRedactedSecret() {
  442. return true
  443. }
  444. }
  445. return u.Filters.TOTPConfig.Secret.IsRedacted()
  446. }
  447. // CloseFs closes the underlying filesystems
  448. func (u *User) CloseFs() error {
  449. if u.fsCache == nil {
  450. return nil
  451. }
  452. var err error
  453. for _, fs := range u.fsCache {
  454. errClose := fs.Close()
  455. if err == nil {
  456. err = errClose
  457. }
  458. }
  459. return err
  460. }
  461. // IsPasswordHashed returns true if the password is hashed
  462. func (u *User) IsPasswordHashed() bool {
  463. return util.IsStringPrefixInSlice(u.Password, hashPwdPrefixes)
  464. }
  465. // IsTLSVerificationEnabled returns true if we need to check the TLS authentication
  466. func (u *User) IsTLSVerificationEnabled() bool {
  467. if len(u.Filters.TLSCerts) > 0 {
  468. return true
  469. }
  470. if u.Filters.TLSUsername != "" {
  471. return u.Filters.TLSUsername != sdk.TLSUsernameNone
  472. }
  473. return false
  474. }
  475. // SetEmptySecrets sets to empty any user secret
  476. func (u *User) SetEmptySecrets() {
  477. u.FsConfig.SetEmptySecrets()
  478. for idx := range u.VirtualFolders {
  479. folder := &u.VirtualFolders[idx]
  480. folder.FsConfig.SetEmptySecrets()
  481. }
  482. u.Filters.TOTPConfig.Secret = kms.NewEmptySecret()
  483. }
  484. // GetPermissionsForPath returns the permissions for the given path.
  485. // The path must be a SFTPGo virtual path
  486. func (u *User) GetPermissionsForPath(p string) []string {
  487. permissions := []string{}
  488. if perms, ok := u.Permissions["/"]; ok {
  489. // if only root permissions are defined returns them unconditionally
  490. if len(u.Permissions) == 1 {
  491. return perms
  492. }
  493. // fallback permissions
  494. permissions = perms
  495. }
  496. dirsForPath := util.GetDirsForVirtualPath(p)
  497. // dirsForPath contains all the dirs for a given path in reverse order
  498. // for example if the path is: /1/2/3/4 it contains:
  499. // [ "/1/2/3/4", "/1/2/3", "/1/2", "/1", "/" ]
  500. // so the first match is the one we are interested to
  501. for idx := range dirsForPath {
  502. if perms, ok := u.Permissions[dirsForPath[idx]]; ok {
  503. return perms
  504. }
  505. for dir, perms := range u.Permissions {
  506. if match, err := path.Match(dir, dirsForPath[idx]); err == nil && match {
  507. return perms
  508. }
  509. }
  510. }
  511. return permissions
  512. }
  513. func (u *User) getForbiddenSFTPSelfUsers(username string) ([]string, error) {
  514. if allowSelfConnections == 0 {
  515. return nil, nil
  516. }
  517. sftpUser, err := UserExists(username, "")
  518. if err == nil {
  519. err = sftpUser.LoadAndApplyGroupSettings()
  520. }
  521. if err == nil {
  522. // we don't allow local nested SFTP folders
  523. var forbiddens []string
  524. if sftpUser.FsConfig.Provider == sdk.SFTPFilesystemProvider {
  525. forbiddens = append(forbiddens, sftpUser.Username)
  526. return forbiddens, nil
  527. }
  528. for idx := range sftpUser.VirtualFolders {
  529. v := &sftpUser.VirtualFolders[idx]
  530. if v.FsConfig.Provider == sdk.SFTPFilesystemProvider {
  531. forbiddens = append(forbiddens, sftpUser.Username)
  532. return forbiddens, nil
  533. }
  534. }
  535. return forbiddens, nil
  536. }
  537. if !errors.Is(err, util.ErrNotFound) {
  538. return nil, err
  539. }
  540. return nil, nil
  541. }
  542. // GetFsConfigForPath returns the file system configuration for the specified virtual path
  543. func (u *User) GetFsConfigForPath(virtualPath string) vfs.Filesystem {
  544. if virtualPath != "" && virtualPath != "/" && len(u.VirtualFolders) > 0 {
  545. folder, err := u.GetVirtualFolderForPath(virtualPath)
  546. if err == nil {
  547. return folder.FsConfig
  548. }
  549. }
  550. return u.FsConfig
  551. }
  552. // GetFilesystemForPath returns the filesystem for the given path
  553. func (u *User) GetFilesystemForPath(virtualPath, connectionID string) (vfs.Fs, error) {
  554. if u.fsCache == nil {
  555. u.fsCache = make(map[string]vfs.Fs)
  556. }
  557. // allow to override the `/` path with a virtual folder
  558. if len(u.VirtualFolders) > 0 {
  559. folder, err := u.GetVirtualFolderForPath(virtualPath)
  560. if err == nil {
  561. if fs, ok := u.fsCache[folder.VirtualPath]; ok {
  562. return fs, nil
  563. }
  564. forbiddenSelfUsers := []string{u.Username}
  565. if folder.FsConfig.Provider == sdk.SFTPFilesystemProvider {
  566. forbiddens, err := u.getForbiddenSFTPSelfUsers(folder.FsConfig.SFTPConfig.Username)
  567. if err != nil {
  568. return nil, err
  569. }
  570. forbiddenSelfUsers = append(forbiddenSelfUsers, forbiddens...)
  571. }
  572. fs, err := folder.GetFilesystem(connectionID, forbiddenSelfUsers)
  573. if err == nil {
  574. u.fsCache[folder.VirtualPath] = fs
  575. }
  576. return fs, err
  577. }
  578. }
  579. if val, ok := u.fsCache["/"]; ok {
  580. return val, nil
  581. }
  582. fs, err := u.getRootFs(connectionID)
  583. if err != nil {
  584. return fs, err
  585. }
  586. u.fsCache["/"] = fs
  587. return fs, err
  588. }
  589. // GetVirtualFolderForPath returns the virtual folder containing the specified virtual path.
  590. // If the path is not inside a virtual folder an error is returned
  591. func (u *User) GetVirtualFolderForPath(virtualPath string) (vfs.VirtualFolder, error) {
  592. var folder vfs.VirtualFolder
  593. if len(u.VirtualFolders) == 0 {
  594. return folder, errNoMatchingVirtualFolder
  595. }
  596. dirsForPath := util.GetDirsForVirtualPath(virtualPath)
  597. for index := range dirsForPath {
  598. for idx := range u.VirtualFolders {
  599. v := &u.VirtualFolders[idx]
  600. if v.VirtualPath == dirsForPath[index] {
  601. return *v, nil
  602. }
  603. }
  604. }
  605. return folder, errNoMatchingVirtualFolder
  606. }
  607. // ScanQuota scans the user home dir and virtual folders, included in its quota,
  608. // and returns the number of files and their size
  609. func (u *User) ScanQuota() (int, int64, error) {
  610. fs, err := u.getRootFs(xid.New().String())
  611. if err != nil {
  612. return 0, 0, err
  613. }
  614. defer fs.Close()
  615. numFiles, size, err := fs.ScanRootDirContents()
  616. if err != nil {
  617. return numFiles, size, err
  618. }
  619. for idx := range u.VirtualFolders {
  620. v := &u.VirtualFolders[idx]
  621. if !v.IsIncludedInUserQuota() {
  622. continue
  623. }
  624. num, s, err := v.ScanQuota()
  625. if err != nil {
  626. return numFiles, size, err
  627. }
  628. numFiles += num
  629. size += s
  630. }
  631. return numFiles, size, nil
  632. }
  633. // GetVirtualFoldersInPath returns the virtual folders inside virtualPath including
  634. // any parents
  635. func (u *User) GetVirtualFoldersInPath(virtualPath string) map[string]bool {
  636. result := make(map[string]bool)
  637. for idx := range u.VirtualFolders {
  638. dirsForPath := util.GetDirsForVirtualPath(u.VirtualFolders[idx].VirtualPath)
  639. for index := range dirsForPath {
  640. d := dirsForPath[index]
  641. if d == "/" {
  642. continue
  643. }
  644. if path.Dir(d) == virtualPath {
  645. result[d] = true
  646. }
  647. }
  648. }
  649. if u.Filters.StartDirectory != "" {
  650. dirsForPath := util.GetDirsForVirtualPath(u.Filters.StartDirectory)
  651. for index := range dirsForPath {
  652. d := dirsForPath[index]
  653. if d == "/" {
  654. continue
  655. }
  656. if path.Dir(d) == virtualPath {
  657. result[d] = true
  658. }
  659. }
  660. }
  661. return result
  662. }
  663. func (u *User) hasVirtualDirs() bool {
  664. if u.Filters.StartDirectory != "" {
  665. return true
  666. }
  667. numFolders := len(u.VirtualFolders)
  668. if numFolders == 1 {
  669. return u.VirtualFolders[0].VirtualPath != "/"
  670. }
  671. return numFolders > 0
  672. }
  673. // GetVirtualFoldersInfo returns []os.FileInfo for virtual folders
  674. func (u *User) GetVirtualFoldersInfo(virtualPath string) []os.FileInfo {
  675. filter := u.getPatternsFilterForPath(virtualPath)
  676. if !u.hasVirtualDirs() && filter.DenyPolicy != sdk.DenyPolicyHide {
  677. return nil
  678. }
  679. vdirs := u.GetVirtualFoldersInPath(virtualPath)
  680. result := make([]os.FileInfo, 0, len(vdirs))
  681. for dir := range u.GetVirtualFoldersInPath(virtualPath) {
  682. dirName := path.Base(dir)
  683. if filter.DenyPolicy == sdk.DenyPolicyHide {
  684. if !filter.CheckAllowed(dirName) {
  685. continue
  686. }
  687. }
  688. result = append(result, vfs.NewFileInfo(dirName, true, 0, time.Unix(0, 0), false))
  689. }
  690. return result
  691. }
  692. // FilterListDir removes hidden items from the given files list
  693. func (u *User) FilterListDir(dirContents []os.FileInfo, virtualPath string) []os.FileInfo {
  694. filter := u.getPatternsFilterForPath(virtualPath)
  695. if !u.hasVirtualDirs() && filter.DenyPolicy != sdk.DenyPolicyHide {
  696. return dirContents
  697. }
  698. vdirs := make(map[string]bool)
  699. for dir := range u.GetVirtualFoldersInPath(virtualPath) {
  700. dirName := path.Base(dir)
  701. if filter.DenyPolicy == sdk.DenyPolicyHide {
  702. if !filter.CheckAllowed(dirName) {
  703. continue
  704. }
  705. }
  706. vdirs[dirName] = true
  707. }
  708. validIdx := 0
  709. for idx := range dirContents {
  710. fi := dirContents[idx]
  711. if fi.Name() != "." && fi.Name() != ".." {
  712. if _, ok := vdirs[fi.Name()]; ok {
  713. continue
  714. }
  715. if filter.DenyPolicy == sdk.DenyPolicyHide {
  716. if !filter.CheckAllowed(fi.Name()) {
  717. continue
  718. }
  719. }
  720. }
  721. dirContents[validIdx] = fi
  722. validIdx++
  723. }
  724. return dirContents[:validIdx]
  725. }
  726. // IsMappedPath returns true if the specified filesystem path has a virtual folder mapping.
  727. // The filesystem path must be cleaned before calling this method
  728. func (u *User) IsMappedPath(fsPath string) bool {
  729. for idx := range u.VirtualFolders {
  730. v := &u.VirtualFolders[idx]
  731. if fsPath == v.MappedPath {
  732. return true
  733. }
  734. }
  735. return false
  736. }
  737. // IsVirtualFolder returns true if the specified virtual path is a virtual folder
  738. func (u *User) IsVirtualFolder(virtualPath string) bool {
  739. for idx := range u.VirtualFolders {
  740. v := &u.VirtualFolders[idx]
  741. if virtualPath == v.VirtualPath {
  742. return true
  743. }
  744. }
  745. return false
  746. }
  747. // HasVirtualFoldersInside returns true if there are virtual folders inside the
  748. // specified virtual path. We assume that path are cleaned
  749. func (u *User) HasVirtualFoldersInside(virtualPath string) bool {
  750. if virtualPath == "/" && len(u.VirtualFolders) > 0 {
  751. return true
  752. }
  753. for idx := range u.VirtualFolders {
  754. v := &u.VirtualFolders[idx]
  755. if len(v.VirtualPath) > len(virtualPath) {
  756. if strings.HasPrefix(v.VirtualPath, virtualPath+"/") {
  757. return true
  758. }
  759. }
  760. }
  761. return false
  762. }
  763. // HasPermissionsInside returns true if the specified virtualPath has no permissions itself and
  764. // no subdirs with defined permissions
  765. func (u *User) HasPermissionsInside(virtualPath string) bool {
  766. for dir, perms := range u.Permissions {
  767. if len(perms) == 1 && perms[0] == PermAny {
  768. continue
  769. }
  770. if dir == virtualPath {
  771. return true
  772. } else if len(dir) > len(virtualPath) {
  773. if strings.HasPrefix(dir, virtualPath+"/") {
  774. return true
  775. }
  776. }
  777. }
  778. return false
  779. }
  780. // HasPerm returns true if the user has the given permission or any permission
  781. func (u *User) HasPerm(permission, path string) bool {
  782. perms := u.GetPermissionsForPath(path)
  783. if slices.Contains(perms, PermAny) {
  784. return true
  785. }
  786. return slices.Contains(perms, permission)
  787. }
  788. // HasAnyPerm returns true if the user has at least one of the given permissions
  789. func (u *User) HasAnyPerm(permissions []string, path string) bool {
  790. perms := u.GetPermissionsForPath(path)
  791. if slices.Contains(perms, PermAny) {
  792. return true
  793. }
  794. for _, permission := range permissions {
  795. if slices.Contains(perms, permission) {
  796. return true
  797. }
  798. }
  799. return false
  800. }
  801. // HasPerms returns true if the user has all the given permissions
  802. func (u *User) HasPerms(permissions []string, path string) bool {
  803. perms := u.GetPermissionsForPath(path)
  804. if slices.Contains(perms, PermAny) {
  805. return true
  806. }
  807. for _, permission := range permissions {
  808. if !slices.Contains(perms, permission) {
  809. return false
  810. }
  811. }
  812. return true
  813. }
  814. // HasPermsDeleteAll returns true if the user can delete both files and directories
  815. // for the given path
  816. func (u *User) HasPermsDeleteAll(path string) bool {
  817. perms := u.GetPermissionsForPath(path)
  818. canDeleteFiles := false
  819. canDeleteDirs := false
  820. for _, permission := range perms {
  821. if permission == PermAny || permission == PermDelete {
  822. return true
  823. }
  824. if permission == PermDeleteFiles {
  825. canDeleteFiles = true
  826. }
  827. if permission == PermDeleteDirs {
  828. canDeleteDirs = true
  829. }
  830. }
  831. return canDeleteFiles && canDeleteDirs
  832. }
  833. // HasPermsRenameAll returns true if the user can rename both files and directories
  834. // for the given path
  835. func (u *User) HasPermsRenameAll(path string) bool {
  836. perms := u.GetPermissionsForPath(path)
  837. canRenameFiles := false
  838. canRenameDirs := false
  839. for _, permission := range perms {
  840. if permission == PermAny || permission == PermRename {
  841. return true
  842. }
  843. if permission == PermRenameFiles {
  844. canRenameFiles = true
  845. }
  846. if permission == PermRenameDirs {
  847. canRenameDirs = true
  848. }
  849. }
  850. return canRenameFiles && canRenameDirs
  851. }
  852. // HasNoQuotaRestrictions returns true if no quota restrictions need to be applyed
  853. func (u *User) HasNoQuotaRestrictions(checkFiles bool) bool {
  854. if u.QuotaSize == 0 && (!checkFiles || u.QuotaFiles == 0) {
  855. return true
  856. }
  857. return false
  858. }
  859. // IsLoginMethodAllowed returns true if the specified login method is allowed
  860. func (u *User) IsLoginMethodAllowed(loginMethod, protocol string) bool {
  861. if len(u.Filters.DeniedLoginMethods) == 0 {
  862. return true
  863. }
  864. if slices.Contains(u.Filters.DeniedLoginMethods, loginMethod) {
  865. return false
  866. }
  867. if protocol == protocolSSH && loginMethod == LoginMethodPassword {
  868. if slices.Contains(u.Filters.DeniedLoginMethods, SSHLoginMethodPassword) {
  869. return false
  870. }
  871. }
  872. return true
  873. }
  874. // GetNextAuthMethods returns the list of authentications methods that can
  875. // continue for multi-step authentication. We call this method after a
  876. // successful public key authentication.
  877. func (u *User) GetNextAuthMethods() []string {
  878. var methods []string
  879. for _, method := range u.GetAllowedLoginMethods() {
  880. if method == SSHLoginMethodKeyAndPassword {
  881. methods = append(methods, LoginMethodPassword)
  882. }
  883. if method == SSHLoginMethodKeyAndKeyboardInt {
  884. methods = append(methods, SSHLoginMethodKeyboardInteractive)
  885. }
  886. }
  887. return methods
  888. }
  889. // IsPartialAuth returns true if the specified login method is a step for
  890. // a multi-step Authentication.
  891. // We support publickey+password and publickey+keyboard-interactive, so
  892. // only publickey can returns partial success.
  893. // We can have partial success if only multi-step Auth methods are enabled
  894. func (u *User) IsPartialAuth() bool {
  895. for _, method := range u.GetAllowedLoginMethods() {
  896. if method == LoginMethodTLSCertificate || method == LoginMethodTLSCertificateAndPwd ||
  897. method == SSHLoginMethodPassword {
  898. continue
  899. }
  900. if method == LoginMethodPassword && slices.Contains(u.Filters.DeniedLoginMethods, SSHLoginMethodPassword) {
  901. continue
  902. }
  903. if !slices.Contains(SSHMultiStepsLoginMethods, method) {
  904. return false
  905. }
  906. }
  907. return true
  908. }
  909. // GetAllowedLoginMethods returns the allowed login methods
  910. func (u *User) GetAllowedLoginMethods() []string {
  911. var allowedMethods []string
  912. for _, method := range ValidLoginMethods {
  913. if method == SSHLoginMethodPassword {
  914. continue
  915. }
  916. if !slices.Contains(u.Filters.DeniedLoginMethods, method) {
  917. allowedMethods = append(allowedMethods, method)
  918. }
  919. }
  920. return allowedMethods
  921. }
  922. func (u *User) getPatternsFilterForPath(virtualPath string) sdk.PatternsFilter {
  923. var filter sdk.PatternsFilter
  924. if len(u.Filters.FilePatterns) == 0 {
  925. return filter
  926. }
  927. dirsForPath := util.GetDirsForVirtualPath(virtualPath)
  928. for idx, dir := range dirsForPath {
  929. for _, f := range u.Filters.FilePatterns {
  930. if f.Path == dir {
  931. if idx > 0 && len(f.AllowedPatterns) > 0 && len(f.DeniedPatterns) > 0 && f.DeniedPatterns[0] == "*" {
  932. if f.CheckAllowed(path.Base(dirsForPath[idx-1])) {
  933. return filter
  934. }
  935. }
  936. filter = f
  937. break
  938. }
  939. }
  940. if filter.Path != "" {
  941. break
  942. }
  943. }
  944. return filter
  945. }
  946. func (u *User) isDirHidden(virtualPath string) bool {
  947. if len(u.Filters.FilePatterns) == 0 {
  948. return false
  949. }
  950. for _, dirPath := range util.GetDirsForVirtualPath(virtualPath) {
  951. if dirPath == "/" {
  952. return false
  953. }
  954. filter := u.getPatternsFilterForPath(dirPath)
  955. if filter.DenyPolicy == sdk.DenyPolicyHide && filter.Path != dirPath {
  956. if !filter.CheckAllowed(path.Base(dirPath)) {
  957. return true
  958. }
  959. }
  960. }
  961. return false
  962. }
  963. func (u *User) getMinPasswordEntropy() float64 {
  964. if u.Filters.PasswordStrength > 0 {
  965. return float64(u.Filters.PasswordStrength)
  966. }
  967. return config.PasswordValidation.Users.MinEntropy
  968. }
  969. // IsFileAllowed returns true if the specified file is allowed by the file restrictions filters.
  970. // The second parameter returned is the deny policy
  971. func (u *User) IsFileAllowed(virtualPath string) (bool, int) {
  972. dirPath := path.Dir(virtualPath)
  973. if u.isDirHidden(dirPath) {
  974. return false, sdk.DenyPolicyHide
  975. }
  976. filter := u.getPatternsFilterForPath(dirPath)
  977. return filter.CheckAllowed(path.Base(virtualPath)), filter.DenyPolicy
  978. }
  979. // CanManageMFA returns true if the user can add a multi-factor authentication configuration
  980. func (u *User) CanManageMFA() bool {
  981. if slices.Contains(u.Filters.WebClient, sdk.WebClientMFADisabled) {
  982. return false
  983. }
  984. return len(mfa.GetAvailableTOTPConfigs()) > 0
  985. }
  986. func (u *User) skipExternalAuth() bool {
  987. if u.Filters.Hooks.ExternalAuthDisabled {
  988. return true
  989. }
  990. if u.ID <= 0 {
  991. return false
  992. }
  993. if u.Filters.ExternalAuthCacheTime <= 0 {
  994. return false
  995. }
  996. return isLastActivityRecent(u.LastLogin, time.Duration(u.Filters.ExternalAuthCacheTime)*time.Second)
  997. }
  998. // CanManageShares returns true if the user can add, update and list shares
  999. func (u *User) CanManageShares() bool {
  1000. return !slices.Contains(u.Filters.WebClient, sdk.WebClientSharesDisabled)
  1001. }
  1002. // CanResetPassword returns true if this user is allowed to reset its password
  1003. func (u *User) CanResetPassword() bool {
  1004. return !slices.Contains(u.Filters.WebClient, sdk.WebClientPasswordResetDisabled)
  1005. }
  1006. // CanChangePassword returns true if this user is allowed to change its password
  1007. func (u *User) CanChangePassword() bool {
  1008. return !slices.Contains(u.Filters.WebClient, sdk.WebClientPasswordChangeDisabled)
  1009. }
  1010. // CanChangeAPIKeyAuth returns true if this user is allowed to enable/disable API key authentication
  1011. func (u *User) CanChangeAPIKeyAuth() bool {
  1012. return !slices.Contains(u.Filters.WebClient, sdk.WebClientAPIKeyAuthChangeDisabled)
  1013. }
  1014. // CanChangeInfo returns true if this user is allowed to change its info such as email and description
  1015. func (u *User) CanChangeInfo() bool {
  1016. return !slices.Contains(u.Filters.WebClient, sdk.WebClientInfoChangeDisabled)
  1017. }
  1018. // CanManagePublicKeys returns true if this user is allowed to manage public keys
  1019. // from the WebClient. Used in WebClient UI
  1020. func (u *User) CanManagePublicKeys() bool {
  1021. return !slices.Contains(u.Filters.WebClient, sdk.WebClientPubKeyChangeDisabled)
  1022. }
  1023. // CanManageTLSCerts returns true if this user is allowed to manage TLS certificates
  1024. // from the WebClient. Used in WebClient UI
  1025. func (u *User) CanManageTLSCerts() bool {
  1026. return !slices.Contains(u.Filters.WebClient, sdk.WebClientTLSCertChangeDisabled)
  1027. }
  1028. // CanUpdateProfile returns true if the user is allowed to update the profile.
  1029. // Used in WebClient UI
  1030. func (u *User) CanUpdateProfile() bool {
  1031. return u.CanManagePublicKeys() || u.CanChangeAPIKeyAuth() || u.CanChangeInfo() || u.CanManageTLSCerts()
  1032. }
  1033. // CanAddFilesFromWeb returns true if the client can add files from the web UI.
  1034. // The specified target is the directory where the files must be uploaded
  1035. func (u *User) CanAddFilesFromWeb(target string) bool {
  1036. if slices.Contains(u.Filters.WebClient, sdk.WebClientWriteDisabled) {
  1037. return false
  1038. }
  1039. return u.HasPerm(PermUpload, target) || u.HasPerm(PermOverwrite, target)
  1040. }
  1041. // CanAddDirsFromWeb returns true if the client can add directories from the web UI.
  1042. // The specified target is the directory where the new directory must be created
  1043. func (u *User) CanAddDirsFromWeb(target string) bool {
  1044. if slices.Contains(u.Filters.WebClient, sdk.WebClientWriteDisabled) {
  1045. return false
  1046. }
  1047. return u.HasPerm(PermCreateDirs, target)
  1048. }
  1049. // CanRenameFromWeb returns true if the client can rename objects from the web UI.
  1050. // The specified src and dest are the source and target directories for the rename.
  1051. func (u *User) CanRenameFromWeb(src, dest string) bool {
  1052. if slices.Contains(u.Filters.WebClient, sdk.WebClientWriteDisabled) {
  1053. return false
  1054. }
  1055. return u.HasAnyPerm(permsRenameAny, src) && u.HasAnyPerm(permsRenameAny, dest)
  1056. }
  1057. // CanDeleteFromWeb returns true if the client can delete objects from the web UI.
  1058. // The specified target is the parent directory for the object to delete
  1059. func (u *User) CanDeleteFromWeb(target string) bool {
  1060. if slices.Contains(u.Filters.WebClient, sdk.WebClientWriteDisabled) {
  1061. return false
  1062. }
  1063. return u.HasAnyPerm(permsDeleteAny, target)
  1064. }
  1065. // CanCopyFromWeb returns true if the client can copy objects from the web UI.
  1066. // The specified src and dest are the source and target directories for the copy.
  1067. func (u *User) CanCopyFromWeb(src, dest string) bool {
  1068. if slices.Contains(u.Filters.WebClient, sdk.WebClientWriteDisabled) {
  1069. return false
  1070. }
  1071. if !u.HasPerm(PermListItems, src) {
  1072. return false
  1073. }
  1074. if !u.HasPerm(PermDownload, src) {
  1075. return false
  1076. }
  1077. return u.HasPerm(PermCopy, src) && u.HasPerm(PermCopy, dest)
  1078. }
  1079. // InactivityDays returns the number of days of inactivity
  1080. func (u *User) InactivityDays(when time.Time) int {
  1081. if when.IsZero() {
  1082. when = time.Now()
  1083. }
  1084. lastActivity := u.LastLogin
  1085. if lastActivity == 0 {
  1086. lastActivity = u.CreatedAt
  1087. }
  1088. if lastActivity == 0 {
  1089. // unable to determine inactivity
  1090. return 0
  1091. }
  1092. return int(float64(when.Sub(util.GetTimeFromMsecSinceEpoch(lastActivity))) / float64(24*time.Hour))
  1093. }
  1094. // PasswordExpiresIn returns the number of days before the password expires.
  1095. // The returned value is negative if the password is expired.
  1096. // The caller must ensure that a PasswordExpiration is set
  1097. func (u *User) PasswordExpiresIn() int {
  1098. lastPwdChange := util.GetTimeFromMsecSinceEpoch(u.LastPasswordChange)
  1099. pwdExpiration := lastPwdChange.Add(time.Duration(u.Filters.PasswordExpiration) * 24 * time.Hour)
  1100. res := int(math.Round(float64(time.Until(pwdExpiration)) / float64(24*time.Hour)))
  1101. if res == 0 && pwdExpiration.After(time.Now()) {
  1102. res = 1
  1103. }
  1104. return res
  1105. }
  1106. // MustChangePassword returns true if the user must change the password
  1107. func (u *User) MustChangePassword() bool {
  1108. if u.Filters.RequirePasswordChange {
  1109. return true
  1110. }
  1111. if u.Filters.PasswordExpiration == 0 {
  1112. return false
  1113. }
  1114. lastPwdChange := util.GetTimeFromMsecSinceEpoch(u.LastPasswordChange)
  1115. return lastPwdChange.Add(time.Duration(u.Filters.PasswordExpiration) * 24 * time.Hour).Before(time.Now())
  1116. }
  1117. // MustSetSecondFactor returns true if the user must set a second factor authentication
  1118. func (u *User) MustSetSecondFactor() bool {
  1119. if len(u.Filters.TwoFactorAuthProtocols) > 0 {
  1120. if !u.Filters.TOTPConfig.Enabled {
  1121. return true
  1122. }
  1123. for _, p := range u.Filters.TwoFactorAuthProtocols {
  1124. if !slices.Contains(u.Filters.TOTPConfig.Protocols, p) {
  1125. return true
  1126. }
  1127. }
  1128. }
  1129. return false
  1130. }
  1131. // MustSetSecondFactorForProtocol returns true if the user must set a second factor authentication
  1132. // for the specified protocol
  1133. func (u *User) MustSetSecondFactorForProtocol(protocol string) bool {
  1134. if slices.Contains(u.Filters.TwoFactorAuthProtocols, protocol) {
  1135. if !u.Filters.TOTPConfig.Enabled {
  1136. return true
  1137. }
  1138. if !slices.Contains(u.Filters.TOTPConfig.Protocols, protocol) {
  1139. return true
  1140. }
  1141. }
  1142. return false
  1143. }
  1144. // GetSignature returns a signature for this user.
  1145. // It will change after an update
  1146. func (u *User) GetSignature() string {
  1147. return strconv.FormatInt(u.UpdatedAt, 10)
  1148. }
  1149. // GetBandwidthForIP returns the upload and download bandwidth for the specified IP
  1150. func (u *User) GetBandwidthForIP(clientIP, connectionID string) (int64, int64) {
  1151. if len(u.Filters.BandwidthLimits) > 0 {
  1152. ip := net.ParseIP(clientIP)
  1153. if ip != nil {
  1154. for _, bwLimit := range u.Filters.BandwidthLimits {
  1155. for _, source := range bwLimit.Sources {
  1156. _, ipNet, err := net.ParseCIDR(source)
  1157. if err == nil {
  1158. if ipNet.Contains(ip) {
  1159. logger.Debug(logSender, connectionID, "override bandwidth limit for ip %q, upload limit: %v KB/s, download limit: %v KB/s",
  1160. clientIP, bwLimit.UploadBandwidth, bwLimit.DownloadBandwidth)
  1161. return bwLimit.UploadBandwidth, bwLimit.DownloadBandwidth
  1162. }
  1163. }
  1164. }
  1165. }
  1166. }
  1167. }
  1168. return u.UploadBandwidth, u.DownloadBandwidth
  1169. }
  1170. // IsLoginFromAddrAllowed returns true if the login is allowed from the specified remoteAddr.
  1171. // If AllowedIP is defined only the specified IP/Mask can login.
  1172. // If DeniedIP is defined the specified IP/Mask cannot login.
  1173. // If an IP is both allowed and denied then login will be allowed
  1174. func (u *User) IsLoginFromAddrAllowed(remoteAddr string) bool {
  1175. if len(u.Filters.AllowedIP) == 0 && len(u.Filters.DeniedIP) == 0 {
  1176. return true
  1177. }
  1178. remoteIP := net.ParseIP(util.GetIPFromRemoteAddress(remoteAddr))
  1179. // if remoteIP is invalid we allow login, this should never happen
  1180. if remoteIP == nil {
  1181. logger.Warn(logSender, "", "login allowed for invalid IP. remote address: %q", remoteAddr)
  1182. return true
  1183. }
  1184. for _, IPMask := range u.Filters.AllowedIP {
  1185. _, IPNet, err := net.ParseCIDR(IPMask)
  1186. if err != nil {
  1187. return false
  1188. }
  1189. if IPNet.Contains(remoteIP) {
  1190. return true
  1191. }
  1192. }
  1193. for _, IPMask := range u.Filters.DeniedIP {
  1194. _, IPNet, err := net.ParseCIDR(IPMask)
  1195. if err != nil {
  1196. return false
  1197. }
  1198. if IPNet.Contains(remoteIP) {
  1199. return false
  1200. }
  1201. }
  1202. return len(u.Filters.AllowedIP) == 0
  1203. }
  1204. // GetPermissionsAsJSON returns the permissions as json byte array
  1205. func (u *User) GetPermissionsAsJSON() ([]byte, error) {
  1206. return json.Marshal(u.Permissions)
  1207. }
  1208. // GetPublicKeysAsJSON returns the public keys as json byte array
  1209. func (u *User) GetPublicKeysAsJSON() ([]byte, error) {
  1210. return json.Marshal(u.PublicKeys)
  1211. }
  1212. // GetFiltersAsJSON returns the filters as json byte array
  1213. func (u *User) GetFiltersAsJSON() ([]byte, error) {
  1214. return json.Marshal(u.Filters)
  1215. }
  1216. // GetFsConfigAsJSON returns the filesystem config as json byte array
  1217. func (u *User) GetFsConfigAsJSON() ([]byte, error) {
  1218. return json.Marshal(u.FsConfig)
  1219. }
  1220. // GetUID returns a validate uid, suitable for use with os.Chown
  1221. func (u *User) GetUID() int {
  1222. if u.UID <= 0 || u.UID > math.MaxInt32 {
  1223. return -1
  1224. }
  1225. return u.UID
  1226. }
  1227. // GetGID returns a validate gid, suitable for use with os.Chown
  1228. func (u *User) GetGID() int {
  1229. if u.GID <= 0 || u.GID > math.MaxInt32 {
  1230. return -1
  1231. }
  1232. return u.GID
  1233. }
  1234. // GetHomeDir returns the shortest path name equivalent to the user's home directory
  1235. func (u *User) GetHomeDir() string {
  1236. return u.HomeDir
  1237. }
  1238. // HasRecentActivity returns true if the last user login is recent and so we can skip some expensive checks
  1239. func (u *User) HasRecentActivity() bool {
  1240. return isLastActivityRecent(u.LastLogin, lastLoginMinDelay)
  1241. }
  1242. // HasQuotaRestrictions returns true if there are any disk quota restrictions
  1243. func (u *User) HasQuotaRestrictions() bool {
  1244. return u.QuotaFiles > 0 || u.QuotaSize > 0
  1245. }
  1246. // HasTransferQuotaRestrictions returns true if there are any data transfer restrictions
  1247. func (u *User) HasTransferQuotaRestrictions() bool {
  1248. return u.UploadDataTransfer > 0 || u.TotalDataTransfer > 0 || u.DownloadDataTransfer > 0
  1249. }
  1250. // GetDataTransferLimits returns upload, download and total data transfer limits
  1251. func (u *User) GetDataTransferLimits() (int64, int64, int64) {
  1252. var total, ul, dl int64
  1253. if u.TotalDataTransfer > 0 {
  1254. total = u.TotalDataTransfer * 1048576
  1255. }
  1256. if u.DownloadDataTransfer > 0 {
  1257. dl = u.DownloadDataTransfer * 1048576
  1258. }
  1259. if u.UploadDataTransfer > 0 {
  1260. ul = u.UploadDataTransfer * 1048576
  1261. }
  1262. return ul, dl, total
  1263. }
  1264. // GetAllowedIPAsString returns the allowed IP as comma separated string
  1265. func (u *User) GetAllowedIPAsString() string {
  1266. return strings.Join(u.Filters.AllowedIP, ",")
  1267. }
  1268. // GetDeniedIPAsString returns the denied IP as comma separated string
  1269. func (u *User) GetDeniedIPAsString() string {
  1270. return strings.Join(u.Filters.DeniedIP, ",")
  1271. }
  1272. // HasExternalAuth returns true if the external authentication is globally enabled
  1273. // and it is not disabled for this user
  1274. func (u *User) HasExternalAuth() bool {
  1275. if u.Filters.Hooks.ExternalAuthDisabled {
  1276. return false
  1277. }
  1278. if config.ExternalAuthHook != "" {
  1279. return true
  1280. }
  1281. return plugin.Handler.HasAuthenticators()
  1282. }
  1283. // CountUnusedRecoveryCodes returns the number of unused recovery codes
  1284. func (u *User) CountUnusedRecoveryCodes() int {
  1285. unused := 0
  1286. for _, code := range u.Filters.RecoveryCodes {
  1287. if !code.Used {
  1288. unused++
  1289. }
  1290. }
  1291. return unused
  1292. }
  1293. // SetEmptySecretsIfNil sets the secrets to empty if nil
  1294. func (u *User) SetEmptySecretsIfNil() {
  1295. u.HasPassword = u.Password != ""
  1296. u.FsConfig.SetEmptySecretsIfNil()
  1297. for idx := range u.VirtualFolders {
  1298. vfolder := &u.VirtualFolders[idx]
  1299. vfolder.FsConfig.SetEmptySecretsIfNil()
  1300. }
  1301. if u.Filters.TOTPConfig.Secret == nil {
  1302. u.Filters.TOTPConfig.Secret = kms.NewEmptySecret()
  1303. }
  1304. }
  1305. func (u *User) hasMainDataTransferLimits() bool {
  1306. return u.UploadDataTransfer > 0 || u.DownloadDataTransfer > 0 || u.TotalDataTransfer > 0
  1307. }
  1308. // HasPrimaryGroup returns true if the user has the specified primary group
  1309. func (u *User) HasPrimaryGroup(name string) bool {
  1310. for _, g := range u.Groups {
  1311. if g.Name == name {
  1312. return g.Type == sdk.GroupTypePrimary
  1313. }
  1314. }
  1315. return false
  1316. }
  1317. // HasSecondaryGroup returns true if the user has the specified secondary group
  1318. func (u *User) HasSecondaryGroup(name string) bool {
  1319. for _, g := range u.Groups {
  1320. if g.Name == name {
  1321. return g.Type == sdk.GroupTypeSecondary
  1322. }
  1323. }
  1324. return false
  1325. }
  1326. // HasMembershipGroup returns true if the user has the specified membership group
  1327. func (u *User) HasMembershipGroup(name string) bool {
  1328. for _, g := range u.Groups {
  1329. if g.Name == name {
  1330. return g.Type == sdk.GroupTypeMembership
  1331. }
  1332. }
  1333. return false
  1334. }
  1335. func (u *User) hasSettingsFromGroups() bool {
  1336. for _, g := range u.Groups {
  1337. if g.Type != sdk.GroupTypeMembership {
  1338. return true
  1339. }
  1340. }
  1341. return false
  1342. }
  1343. func (u *User) applyGroupSettings(groupsMapping map[string]Group) {
  1344. if !u.hasSettingsFromGroups() {
  1345. return
  1346. }
  1347. if u.groupSettingsApplied {
  1348. return
  1349. }
  1350. replacer := u.getGroupPlacehodersReplacer()
  1351. for _, g := range u.Groups {
  1352. if g.Type == sdk.GroupTypePrimary {
  1353. if group, ok := groupsMapping[g.Name]; ok {
  1354. u.mergeWithPrimaryGroup(&group, replacer)
  1355. } else {
  1356. providerLog(logger.LevelError, "mapping not found for user %s, group %s", u.Username, g.Name)
  1357. }
  1358. break
  1359. }
  1360. }
  1361. for _, g := range u.Groups {
  1362. if g.Type == sdk.GroupTypeSecondary {
  1363. if group, ok := groupsMapping[g.Name]; ok {
  1364. u.mergeAdditiveProperties(&group, sdk.GroupTypeSecondary, replacer)
  1365. } else {
  1366. providerLog(logger.LevelError, "mapping not found for user %s, group %s", u.Username, g.Name)
  1367. }
  1368. }
  1369. }
  1370. u.removeDuplicatesAfterGroupMerge()
  1371. }
  1372. // LoadAndApplyGroupSettings update the user by loading and applying the group settings
  1373. func (u *User) LoadAndApplyGroupSettings() error {
  1374. if !u.hasSettingsFromGroups() {
  1375. return nil
  1376. }
  1377. if u.groupSettingsApplied {
  1378. return nil
  1379. }
  1380. names := make([]string, 0, len(u.Groups))
  1381. var primaryGroupName string
  1382. for _, g := range u.Groups {
  1383. if g.Type == sdk.GroupTypePrimary {
  1384. primaryGroupName = g.Name
  1385. }
  1386. if g.Type != sdk.GroupTypeMembership {
  1387. names = append(names, g.Name)
  1388. }
  1389. }
  1390. groups, err := provider.getGroupsWithNames(names)
  1391. if err != nil {
  1392. return fmt.Errorf("unable to get groups: %w", err)
  1393. }
  1394. replacer := u.getGroupPlacehodersReplacer()
  1395. // make sure to always merge with the primary group first
  1396. for idx := range groups {
  1397. g := groups[idx]
  1398. if g.Name == primaryGroupName {
  1399. u.mergeWithPrimaryGroup(&g, replacer)
  1400. lastIdx := len(groups) - 1
  1401. groups[idx] = groups[lastIdx]
  1402. groups = groups[:lastIdx]
  1403. break
  1404. }
  1405. }
  1406. for idx := range groups {
  1407. g := groups[idx]
  1408. u.mergeAdditiveProperties(&g, sdk.GroupTypeSecondary, replacer)
  1409. }
  1410. u.removeDuplicatesAfterGroupMerge()
  1411. return nil
  1412. }
  1413. func (u *User) getGroupPlacehodersReplacer() *strings.Replacer {
  1414. return strings.NewReplacer("%username%", u.Username, "%role%", u.Role)
  1415. }
  1416. func (u *User) replacePlaceholder(value string, replacer *strings.Replacer) string {
  1417. if value == "" {
  1418. return value
  1419. }
  1420. return replacer.Replace(value)
  1421. }
  1422. func (u *User) replaceFsConfigPlaceholders(fsConfig vfs.Filesystem, replacer *strings.Replacer) vfs.Filesystem {
  1423. switch fsConfig.Provider {
  1424. case sdk.S3FilesystemProvider:
  1425. fsConfig.S3Config.KeyPrefix = u.replacePlaceholder(fsConfig.S3Config.KeyPrefix, replacer)
  1426. case sdk.GCSFilesystemProvider:
  1427. fsConfig.GCSConfig.KeyPrefix = u.replacePlaceholder(fsConfig.GCSConfig.KeyPrefix, replacer)
  1428. case sdk.AzureBlobFilesystemProvider:
  1429. fsConfig.AzBlobConfig.KeyPrefix = u.replacePlaceholder(fsConfig.AzBlobConfig.KeyPrefix, replacer)
  1430. case sdk.SFTPFilesystemProvider:
  1431. fsConfig.SFTPConfig.Username = u.replacePlaceholder(fsConfig.SFTPConfig.Username, replacer)
  1432. fsConfig.SFTPConfig.Prefix = u.replacePlaceholder(fsConfig.SFTPConfig.Prefix, replacer)
  1433. case sdk.HTTPFilesystemProvider:
  1434. fsConfig.HTTPConfig.Username = u.replacePlaceholder(fsConfig.HTTPConfig.Username, replacer)
  1435. }
  1436. return fsConfig
  1437. }
  1438. func (u *User) mergeCryptFsConfig(group *Group) {
  1439. if group.UserSettings.FsConfig.Provider == sdk.CryptedFilesystemProvider {
  1440. if u.FsConfig.CryptConfig.ReadBufferSize == 0 {
  1441. u.FsConfig.CryptConfig.ReadBufferSize = group.UserSettings.FsConfig.CryptConfig.ReadBufferSize
  1442. }
  1443. if u.FsConfig.CryptConfig.WriteBufferSize == 0 {
  1444. u.FsConfig.CryptConfig.WriteBufferSize = group.UserSettings.FsConfig.CryptConfig.WriteBufferSize
  1445. }
  1446. }
  1447. }
  1448. func (u *User) mergeWithPrimaryGroup(group *Group, replacer *strings.Replacer) {
  1449. if group.UserSettings.HomeDir != "" {
  1450. u.HomeDir = u.replacePlaceholder(group.UserSettings.HomeDir, replacer)
  1451. }
  1452. if group.UserSettings.FsConfig.Provider != 0 {
  1453. u.FsConfig = u.replaceFsConfigPlaceholders(group.UserSettings.FsConfig, replacer)
  1454. u.mergeCryptFsConfig(group)
  1455. } else {
  1456. if u.FsConfig.OSConfig.ReadBufferSize == 0 {
  1457. u.FsConfig.OSConfig.ReadBufferSize = group.UserSettings.FsConfig.OSConfig.ReadBufferSize
  1458. }
  1459. if u.FsConfig.OSConfig.WriteBufferSize == 0 {
  1460. u.FsConfig.OSConfig.WriteBufferSize = group.UserSettings.FsConfig.OSConfig.WriteBufferSize
  1461. }
  1462. }
  1463. if u.MaxSessions == 0 {
  1464. u.MaxSessions = group.UserSettings.MaxSessions
  1465. }
  1466. if u.QuotaSize == 0 {
  1467. u.QuotaSize = group.UserSettings.QuotaSize
  1468. }
  1469. if u.QuotaFiles == 0 {
  1470. u.QuotaFiles = group.UserSettings.QuotaFiles
  1471. }
  1472. if u.UploadBandwidth == 0 {
  1473. u.UploadBandwidth = group.UserSettings.UploadBandwidth
  1474. }
  1475. if u.DownloadBandwidth == 0 {
  1476. u.DownloadBandwidth = group.UserSettings.DownloadBandwidth
  1477. }
  1478. if !u.hasMainDataTransferLimits() {
  1479. u.UploadDataTransfer = group.UserSettings.UploadDataTransfer
  1480. u.DownloadDataTransfer = group.UserSettings.DownloadDataTransfer
  1481. u.TotalDataTransfer = group.UserSettings.TotalDataTransfer
  1482. }
  1483. if u.ExpirationDate == 0 && group.UserSettings.ExpiresIn > 0 {
  1484. u.ExpirationDate = u.CreatedAt + int64(group.UserSettings.ExpiresIn)*86400000
  1485. }
  1486. u.mergePrimaryGroupFilters(&group.UserSettings.Filters, replacer)
  1487. u.mergeAdditiveProperties(group, sdk.GroupTypePrimary, replacer)
  1488. }
  1489. func (u *User) mergePrimaryGroupFilters(filters *sdk.BaseUserFilters, replacer *strings.Replacer) { //nolint:gocyclo
  1490. if u.Filters.MaxUploadFileSize == 0 {
  1491. u.Filters.MaxUploadFileSize = filters.MaxUploadFileSize
  1492. }
  1493. if !u.IsTLSVerificationEnabled() {
  1494. u.Filters.TLSUsername = filters.TLSUsername
  1495. }
  1496. if !u.Filters.Hooks.CheckPasswordDisabled {
  1497. u.Filters.Hooks.CheckPasswordDisabled = filters.Hooks.CheckPasswordDisabled
  1498. }
  1499. if !u.Filters.Hooks.PreLoginDisabled {
  1500. u.Filters.Hooks.PreLoginDisabled = filters.Hooks.PreLoginDisabled
  1501. }
  1502. if !u.Filters.Hooks.ExternalAuthDisabled {
  1503. u.Filters.Hooks.ExternalAuthDisabled = filters.Hooks.ExternalAuthDisabled
  1504. }
  1505. if !u.Filters.DisableFsChecks {
  1506. u.Filters.DisableFsChecks = filters.DisableFsChecks
  1507. }
  1508. if !u.Filters.AllowAPIKeyAuth {
  1509. u.Filters.AllowAPIKeyAuth = filters.AllowAPIKeyAuth
  1510. }
  1511. if !u.Filters.IsAnonymous {
  1512. u.Filters.IsAnonymous = filters.IsAnonymous
  1513. }
  1514. if u.Filters.ExternalAuthCacheTime == 0 {
  1515. u.Filters.ExternalAuthCacheTime = filters.ExternalAuthCacheTime
  1516. }
  1517. if u.Filters.FTPSecurity == 0 {
  1518. u.Filters.FTPSecurity = filters.FTPSecurity
  1519. }
  1520. if u.Filters.StartDirectory == "" {
  1521. u.Filters.StartDirectory = u.replacePlaceholder(filters.StartDirectory, replacer)
  1522. }
  1523. if u.Filters.DefaultSharesExpiration == 0 {
  1524. u.Filters.DefaultSharesExpiration = filters.DefaultSharesExpiration
  1525. }
  1526. if u.Filters.MaxSharesExpiration == 0 {
  1527. u.Filters.MaxSharesExpiration = filters.MaxSharesExpiration
  1528. }
  1529. if u.Filters.PasswordExpiration == 0 {
  1530. u.Filters.PasswordExpiration = filters.PasswordExpiration
  1531. }
  1532. if u.Filters.PasswordStrength == 0 {
  1533. u.Filters.PasswordStrength = filters.PasswordStrength
  1534. }
  1535. }
  1536. func (u *User) mergeAdditiveProperties(group *Group, groupType int, replacer *strings.Replacer) {
  1537. u.mergeVirtualFolders(group, groupType, replacer)
  1538. u.mergePermissions(group, groupType, replacer)
  1539. u.mergeFilePatterns(group, groupType, replacer)
  1540. u.Filters.BandwidthLimits = append(u.Filters.BandwidthLimits, group.UserSettings.Filters.BandwidthLimits...)
  1541. u.Filters.AllowedIP = append(u.Filters.AllowedIP, group.UserSettings.Filters.AllowedIP...)
  1542. u.Filters.DeniedIP = append(u.Filters.DeniedIP, group.UserSettings.Filters.DeniedIP...)
  1543. u.Filters.DeniedLoginMethods = append(u.Filters.DeniedLoginMethods, group.UserSettings.Filters.DeniedLoginMethods...)
  1544. u.Filters.DeniedProtocols = append(u.Filters.DeniedProtocols, group.UserSettings.Filters.DeniedProtocols...)
  1545. u.Filters.WebClient = append(u.Filters.WebClient, group.UserSettings.Filters.WebClient...)
  1546. u.Filters.TwoFactorAuthProtocols = append(u.Filters.TwoFactorAuthProtocols, group.UserSettings.Filters.TwoFactorAuthProtocols...)
  1547. u.Filters.AccessTime = append(u.Filters.AccessTime, group.UserSettings.Filters.AccessTime...)
  1548. }
  1549. func (u *User) mergeVirtualFolders(group *Group, groupType int, replacer *strings.Replacer) {
  1550. if len(group.VirtualFolders) > 0 {
  1551. folderPaths := make(map[string]bool)
  1552. for _, folder := range u.VirtualFolders {
  1553. folderPaths[folder.VirtualPath] = true
  1554. }
  1555. for _, folder := range group.VirtualFolders {
  1556. if folder.VirtualPath == "/" && groupType != sdk.GroupTypePrimary {
  1557. continue
  1558. }
  1559. folder.VirtualPath = u.replacePlaceholder(folder.VirtualPath, replacer)
  1560. if _, ok := folderPaths[folder.VirtualPath]; !ok {
  1561. folder.MappedPath = u.replacePlaceholder(folder.MappedPath, replacer)
  1562. folder.FsConfig = u.replaceFsConfigPlaceholders(folder.FsConfig, replacer)
  1563. u.VirtualFolders = append(u.VirtualFolders, folder)
  1564. }
  1565. }
  1566. }
  1567. }
  1568. func (u *User) mergePermissions(group *Group, groupType int, replacer *strings.Replacer) {
  1569. if u.Permissions == nil {
  1570. u.Permissions = make(map[string][]string)
  1571. }
  1572. for k, v := range group.UserSettings.Permissions {
  1573. if k == "/" {
  1574. if groupType == sdk.GroupTypePrimary {
  1575. u.Permissions[k] = v
  1576. } else {
  1577. continue
  1578. }
  1579. }
  1580. k = u.replacePlaceholder(k, replacer)
  1581. if _, ok := u.Permissions[k]; !ok {
  1582. u.Permissions[k] = v
  1583. }
  1584. }
  1585. }
  1586. func (u *User) mergeFilePatterns(group *Group, groupType int, replacer *strings.Replacer) {
  1587. if len(group.UserSettings.Filters.FilePatterns) > 0 {
  1588. patternPaths := make(map[string]bool)
  1589. for _, pattern := range u.Filters.FilePatterns {
  1590. patternPaths[pattern.Path] = true
  1591. }
  1592. for _, pattern := range group.UserSettings.Filters.FilePatterns {
  1593. if pattern.Path == "/" && groupType != sdk.GroupTypePrimary {
  1594. continue
  1595. }
  1596. pattern.Path = u.replacePlaceholder(pattern.Path, replacer)
  1597. if _, ok := patternPaths[pattern.Path]; !ok {
  1598. u.Filters.FilePatterns = append(u.Filters.FilePatterns, pattern)
  1599. }
  1600. }
  1601. }
  1602. }
  1603. func (u *User) removeDuplicatesAfterGroupMerge() {
  1604. u.Filters.AllowedIP = util.RemoveDuplicates(u.Filters.AllowedIP, false)
  1605. u.Filters.DeniedIP = util.RemoveDuplicates(u.Filters.DeniedIP, false)
  1606. u.Filters.DeniedLoginMethods = util.RemoveDuplicates(u.Filters.DeniedLoginMethods, false)
  1607. u.Filters.DeniedProtocols = util.RemoveDuplicates(u.Filters.DeniedProtocols, false)
  1608. u.Filters.WebClient = util.RemoveDuplicates(u.Filters.WebClient, false)
  1609. u.Filters.TwoFactorAuthProtocols = util.RemoveDuplicates(u.Filters.TwoFactorAuthProtocols, false)
  1610. u.SetEmptySecretsIfNil()
  1611. u.groupSettingsApplied = true
  1612. }
  1613. func (u *User) hasRole(role string) bool {
  1614. if role == "" {
  1615. return true
  1616. }
  1617. return role == u.Role
  1618. }
  1619. func (u *User) getACopy() User {
  1620. u.SetEmptySecretsIfNil()
  1621. pubKeys := make([]string, len(u.PublicKeys))
  1622. copy(pubKeys, u.PublicKeys)
  1623. virtualFolders := make([]vfs.VirtualFolder, 0, len(u.VirtualFolders))
  1624. for idx := range u.VirtualFolders {
  1625. vfolder := u.VirtualFolders[idx].GetACopy()
  1626. virtualFolders = append(virtualFolders, vfolder)
  1627. }
  1628. groups := make([]sdk.GroupMapping, 0, len(u.Groups))
  1629. for _, g := range u.Groups {
  1630. groups = append(groups, sdk.GroupMapping{
  1631. Name: g.Name,
  1632. Type: g.Type,
  1633. })
  1634. }
  1635. permissions := make(map[string][]string)
  1636. for k, v := range u.Permissions {
  1637. perms := make([]string, len(v))
  1638. copy(perms, v)
  1639. permissions[k] = perms
  1640. }
  1641. filters := UserFilters{
  1642. BaseUserFilters: copyBaseUserFilters(u.Filters.BaseUserFilters),
  1643. }
  1644. filters.RequirePasswordChange = u.Filters.RequirePasswordChange
  1645. filters.TOTPConfig.Enabled = u.Filters.TOTPConfig.Enabled
  1646. filters.TOTPConfig.ConfigName = u.Filters.TOTPConfig.ConfigName
  1647. filters.TOTPConfig.Secret = u.Filters.TOTPConfig.Secret.Clone()
  1648. filters.TOTPConfig.Protocols = make([]string, len(u.Filters.TOTPConfig.Protocols))
  1649. copy(filters.TOTPConfig.Protocols, u.Filters.TOTPConfig.Protocols)
  1650. filters.RecoveryCodes = make([]RecoveryCode, 0, len(u.Filters.RecoveryCodes))
  1651. for _, code := range u.Filters.RecoveryCodes {
  1652. if code.Secret == nil {
  1653. code.Secret = kms.NewEmptySecret()
  1654. }
  1655. filters.RecoveryCodes = append(filters.RecoveryCodes, RecoveryCode{
  1656. Secret: code.Secret.Clone(),
  1657. Used: code.Used,
  1658. })
  1659. }
  1660. return User{
  1661. BaseUser: sdk.BaseUser{
  1662. ID: u.ID,
  1663. Username: u.Username,
  1664. Email: u.Email,
  1665. Password: u.Password,
  1666. PublicKeys: pubKeys,
  1667. HasPassword: u.HasPassword,
  1668. HomeDir: u.HomeDir,
  1669. UID: u.UID,
  1670. GID: u.GID,
  1671. MaxSessions: u.MaxSessions,
  1672. QuotaSize: u.QuotaSize,
  1673. QuotaFiles: u.QuotaFiles,
  1674. Permissions: permissions,
  1675. UsedQuotaSize: u.UsedQuotaSize,
  1676. UsedQuotaFiles: u.UsedQuotaFiles,
  1677. LastQuotaUpdate: u.LastQuotaUpdate,
  1678. UploadBandwidth: u.UploadBandwidth,
  1679. DownloadBandwidth: u.DownloadBandwidth,
  1680. UploadDataTransfer: u.UploadDataTransfer,
  1681. DownloadDataTransfer: u.DownloadDataTransfer,
  1682. TotalDataTransfer: u.TotalDataTransfer,
  1683. UsedUploadDataTransfer: u.UsedUploadDataTransfer,
  1684. UsedDownloadDataTransfer: u.UsedDownloadDataTransfer,
  1685. Status: u.Status,
  1686. ExpirationDate: u.ExpirationDate,
  1687. LastLogin: u.LastLogin,
  1688. FirstDownload: u.FirstDownload,
  1689. FirstUpload: u.FirstUpload,
  1690. LastPasswordChange: u.LastPasswordChange,
  1691. AdditionalInfo: u.AdditionalInfo,
  1692. Description: u.Description,
  1693. CreatedAt: u.CreatedAt,
  1694. UpdatedAt: u.UpdatedAt,
  1695. Role: u.Role,
  1696. },
  1697. Filters: filters,
  1698. VirtualFolders: virtualFolders,
  1699. Groups: groups,
  1700. FsConfig: u.FsConfig.GetACopy(),
  1701. groupSettingsApplied: u.groupSettingsApplied,
  1702. }
  1703. }
  1704. // GetEncryptionAdditionalData returns the additional data to use for AEAD
  1705. func (u *User) GetEncryptionAdditionalData() string {
  1706. return u.Username
  1707. }