user.go 55 KB

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