user.go 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840
  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, perms := range u.Permissions {
  688. if len(perms) == 1 && perms[0] == PermAny {
  689. continue
  690. }
  691. if dir == virtualPath {
  692. return true
  693. } else if len(dir) > len(virtualPath) {
  694. if strings.HasPrefix(dir, virtualPath+"/") {
  695. return true
  696. }
  697. }
  698. }
  699. return false
  700. }
  701. // HasPerm returns true if the user has the given permission or any permission
  702. func (u *User) HasPerm(permission, path string) bool {
  703. perms := u.GetPermissionsForPath(path)
  704. if util.Contains(perms, PermAny) {
  705. return true
  706. }
  707. return util.Contains(perms, permission)
  708. }
  709. // HasAnyPerm returns true if the user has at least one of the given permissions
  710. func (u *User) HasAnyPerm(permissions []string, path string) bool {
  711. perms := u.GetPermissionsForPath(path)
  712. if util.Contains(perms, PermAny) {
  713. return true
  714. }
  715. for _, permission := range permissions {
  716. if util.Contains(perms, permission) {
  717. return true
  718. }
  719. }
  720. return false
  721. }
  722. // HasPerms returns true if the user has all the given permissions
  723. func (u *User) HasPerms(permissions []string, path string) bool {
  724. perms := u.GetPermissionsForPath(path)
  725. if util.Contains(perms, PermAny) {
  726. return true
  727. }
  728. for _, permission := range permissions {
  729. if !util.Contains(perms, permission) {
  730. return false
  731. }
  732. }
  733. return true
  734. }
  735. // HasPermsDeleteAll returns true if the user can delete both files and directories
  736. // for the given path
  737. func (u *User) HasPermsDeleteAll(path string) bool {
  738. perms := u.GetPermissionsForPath(path)
  739. canDeleteFiles := false
  740. canDeleteDirs := false
  741. for _, permission := range perms {
  742. if permission == PermAny || permission == PermDelete {
  743. return true
  744. }
  745. if permission == PermDeleteFiles {
  746. canDeleteFiles = true
  747. }
  748. if permission == PermDeleteDirs {
  749. canDeleteDirs = true
  750. }
  751. }
  752. return canDeleteFiles && canDeleteDirs
  753. }
  754. // HasPermsRenameAll returns true if the user can rename both files and directories
  755. // for the given path
  756. func (u *User) HasPermsRenameAll(path string) bool {
  757. perms := u.GetPermissionsForPath(path)
  758. canRenameFiles := false
  759. canRenameDirs := false
  760. for _, permission := range perms {
  761. if permission == PermAny || permission == PermRename {
  762. return true
  763. }
  764. if permission == PermRenameFiles {
  765. canRenameFiles = true
  766. }
  767. if permission == PermRenameDirs {
  768. canRenameDirs = true
  769. }
  770. }
  771. return canRenameFiles && canRenameDirs
  772. }
  773. // HasNoQuotaRestrictions returns true if no quota restrictions need to be applyed
  774. func (u *User) HasNoQuotaRestrictions(checkFiles bool) bool {
  775. if u.QuotaSize == 0 && (!checkFiles || u.QuotaFiles == 0) {
  776. return true
  777. }
  778. return false
  779. }
  780. // IsLoginMethodAllowed returns true if the specified login method is allowed
  781. func (u *User) IsLoginMethodAllowed(loginMethod, protocol string, partialSuccessMethods []string) bool {
  782. if len(u.Filters.DeniedLoginMethods) == 0 {
  783. return true
  784. }
  785. if len(partialSuccessMethods) == 1 {
  786. for _, method := range u.GetNextAuthMethods(partialSuccessMethods, true) {
  787. if method == loginMethod {
  788. return true
  789. }
  790. }
  791. }
  792. if util.Contains(u.Filters.DeniedLoginMethods, loginMethod) {
  793. return false
  794. }
  795. if protocol == protocolSSH && loginMethod == LoginMethodPassword {
  796. if util.Contains(u.Filters.DeniedLoginMethods, SSHLoginMethodPassword) {
  797. return false
  798. }
  799. }
  800. return true
  801. }
  802. // GetNextAuthMethods returns the list of authentications methods that
  803. // can continue for multi-step authentication
  804. func (u *User) GetNextAuthMethods(partialSuccessMethods []string, isPasswordAuthEnabled bool) []string {
  805. var methods []string
  806. if len(partialSuccessMethods) != 1 {
  807. return methods
  808. }
  809. if partialSuccessMethods[0] != SSHLoginMethodPublicKey {
  810. return methods
  811. }
  812. for _, method := range u.GetAllowedLoginMethods() {
  813. if method == SSHLoginMethodKeyAndPassword && isPasswordAuthEnabled {
  814. methods = append(methods, LoginMethodPassword)
  815. }
  816. if method == SSHLoginMethodKeyAndKeyboardInt {
  817. methods = append(methods, SSHLoginMethodKeyboardInteractive)
  818. }
  819. }
  820. return methods
  821. }
  822. // IsPartialAuth returns true if the specified login method is a step for
  823. // a multi-step Authentication.
  824. // We support publickey+password and publickey+keyboard-interactive, so
  825. // only publickey can returns partial success.
  826. // We can have partial success if only multi-step Auth methods are enabled
  827. func (u *User) IsPartialAuth(loginMethod string) bool {
  828. if loginMethod != SSHLoginMethodPublicKey {
  829. return false
  830. }
  831. for _, method := range u.GetAllowedLoginMethods() {
  832. if method == LoginMethodTLSCertificate || method == LoginMethodTLSCertificateAndPwd ||
  833. method == SSHLoginMethodPassword {
  834. continue
  835. }
  836. if !util.Contains(SSHMultiStepsLoginMethods, method) {
  837. return false
  838. }
  839. }
  840. return true
  841. }
  842. // GetAllowedLoginMethods returns the allowed login methods
  843. func (u *User) GetAllowedLoginMethods() []string {
  844. var allowedMethods []string
  845. for _, method := range ValidLoginMethods {
  846. if method == SSHLoginMethodPassword {
  847. continue
  848. }
  849. if !util.Contains(u.Filters.DeniedLoginMethods, method) {
  850. allowedMethods = append(allowedMethods, method)
  851. }
  852. }
  853. return allowedMethods
  854. }
  855. func (u *User) getPatternsFilterForPath(virtualPath string) sdk.PatternsFilter {
  856. var filter sdk.PatternsFilter
  857. if len(u.Filters.FilePatterns) == 0 {
  858. return filter
  859. }
  860. dirsForPath := util.GetDirsForVirtualPath(virtualPath)
  861. for _, dir := range dirsForPath {
  862. for _, f := range u.Filters.FilePatterns {
  863. if f.Path == dir {
  864. filter = f
  865. break
  866. }
  867. }
  868. if filter.Path != "" {
  869. break
  870. }
  871. }
  872. return filter
  873. }
  874. func (u *User) isDirHidden(virtualPath string) bool {
  875. if len(u.Filters.FilePatterns) == 0 {
  876. return false
  877. }
  878. for _, dirPath := range util.GetDirsForVirtualPath(virtualPath) {
  879. if dirPath == "/" {
  880. return false
  881. }
  882. filter := u.getPatternsFilterForPath(dirPath)
  883. if filter.DenyPolicy == sdk.DenyPolicyHide {
  884. if !filter.CheckAllowed(path.Base(dirPath)) {
  885. return true
  886. }
  887. }
  888. }
  889. return false
  890. }
  891. // IsFileAllowed returns true if the specified file is allowed by the file restrictions filters.
  892. // The second parameter returned is the deny policy
  893. func (u *User) IsFileAllowed(virtualPath string) (bool, int) {
  894. dirPath := path.Dir(virtualPath)
  895. if u.isDirHidden(dirPath) {
  896. return false, sdk.DenyPolicyHide
  897. }
  898. filter := u.getPatternsFilterForPath(dirPath)
  899. return filter.CheckAllowed(path.Base(virtualPath)), filter.DenyPolicy
  900. }
  901. // CanManageMFA returns true if the user can add a multi-factor authentication configuration
  902. func (u *User) CanManageMFA() bool {
  903. if util.Contains(u.Filters.WebClient, sdk.WebClientMFADisabled) {
  904. return false
  905. }
  906. return len(mfa.GetAvailableTOTPConfigs()) > 0
  907. }
  908. func (u *User) isExternalAuthCached() bool {
  909. if u.ID <= 0 {
  910. return false
  911. }
  912. if u.Filters.ExternalAuthCacheTime <= 0 {
  913. return false
  914. }
  915. return isLastActivityRecent(u.LastLogin, time.Duration(u.Filters.ExternalAuthCacheTime)*time.Second)
  916. }
  917. // CanManageShares returns true if the user can add, update and list shares
  918. func (u *User) CanManageShares() bool {
  919. return !util.Contains(u.Filters.WebClient, sdk.WebClientSharesDisabled)
  920. }
  921. // CanResetPassword returns true if this user is allowed to reset its password
  922. func (u *User) CanResetPassword() bool {
  923. return !util.Contains(u.Filters.WebClient, sdk.WebClientPasswordResetDisabled)
  924. }
  925. // CanChangePassword returns true if this user is allowed to change its password
  926. func (u *User) CanChangePassword() bool {
  927. return !util.Contains(u.Filters.WebClient, sdk.WebClientPasswordChangeDisabled)
  928. }
  929. // CanChangeAPIKeyAuth returns true if this user is allowed to enable/disable API key authentication
  930. func (u *User) CanChangeAPIKeyAuth() bool {
  931. return !util.Contains(u.Filters.WebClient, sdk.WebClientAPIKeyAuthChangeDisabled)
  932. }
  933. // CanChangeInfo returns true if this user is allowed to change its info such as email and description
  934. func (u *User) CanChangeInfo() bool {
  935. return !util.Contains(u.Filters.WebClient, sdk.WebClientInfoChangeDisabled)
  936. }
  937. // CanManagePublicKeys returns true if this user is allowed to manage public keys
  938. // from the web client. Used in web client UI
  939. func (u *User) CanManagePublicKeys() bool {
  940. return !util.Contains(u.Filters.WebClient, sdk.WebClientPubKeyChangeDisabled)
  941. }
  942. // CanAddFilesFromWeb returns true if the client can add files from the web UI.
  943. // The specified target is the directory where the files must be uploaded
  944. func (u *User) CanAddFilesFromWeb(target string) bool {
  945. if util.Contains(u.Filters.WebClient, sdk.WebClientWriteDisabled) {
  946. return false
  947. }
  948. return u.HasPerm(PermUpload, target) || u.HasPerm(PermOverwrite, target)
  949. }
  950. // CanAddDirsFromWeb returns true if the client can add directories from the web UI.
  951. // The specified target is the directory where the new directory must be created
  952. func (u *User) CanAddDirsFromWeb(target string) bool {
  953. if util.Contains(u.Filters.WebClient, sdk.WebClientWriteDisabled) {
  954. return false
  955. }
  956. return u.HasPerm(PermCreateDirs, target)
  957. }
  958. // CanRenameFromWeb returns true if the client can rename objects from the web UI.
  959. // The specified src and dest are the source and target directories for the rename.
  960. func (u *User) CanRenameFromWeb(src, dest string) bool {
  961. if util.Contains(u.Filters.WebClient, sdk.WebClientWriteDisabled) {
  962. return false
  963. }
  964. return u.HasAnyPerm(permsRenameAny, src) && u.HasAnyPerm(permsRenameAny, dest)
  965. }
  966. // CanDeleteFromWeb returns true if the client can delete objects from the web UI.
  967. // The specified target is the parent directory for the object to delete
  968. func (u *User) CanDeleteFromWeb(target string) bool {
  969. if util.Contains(u.Filters.WebClient, sdk.WebClientWriteDisabled) {
  970. return false
  971. }
  972. return u.HasAnyPerm(permsDeleteAny, target)
  973. }
  974. // MustSetSecondFactor returns true if the user must set a second factor authentication
  975. func (u *User) MustSetSecondFactor() bool {
  976. if len(u.Filters.TwoFactorAuthProtocols) > 0 {
  977. if !u.Filters.TOTPConfig.Enabled {
  978. return true
  979. }
  980. for _, p := range u.Filters.TwoFactorAuthProtocols {
  981. if !util.Contains(u.Filters.TOTPConfig.Protocols, p) {
  982. return true
  983. }
  984. }
  985. }
  986. return false
  987. }
  988. // MustSetSecondFactorForProtocol returns true if the user must set a second factor authentication
  989. // for the specified protocol
  990. func (u *User) MustSetSecondFactorForProtocol(protocol string) bool {
  991. if util.Contains(u.Filters.TwoFactorAuthProtocols, protocol) {
  992. if !u.Filters.TOTPConfig.Enabled {
  993. return true
  994. }
  995. if !util.Contains(u.Filters.TOTPConfig.Protocols, protocol) {
  996. return true
  997. }
  998. }
  999. return false
  1000. }
  1001. // GetSignature returns a signature for this admin.
  1002. // It could change after an update
  1003. func (u *User) GetSignature() string {
  1004. data := []byte(fmt.Sprintf("%v_%v_%v", u.Username, u.Status, u.ExpirationDate))
  1005. data = append(data, []byte(u.Password)...)
  1006. signature := sha256.Sum256(data)
  1007. return base64.StdEncoding.EncodeToString(signature[:])
  1008. }
  1009. // GetBandwidthForIP returns the upload and download bandwidth for the specified IP
  1010. func (u *User) GetBandwidthForIP(clientIP, connectionID string) (int64, int64) {
  1011. if len(u.Filters.BandwidthLimits) > 0 {
  1012. ip := net.ParseIP(clientIP)
  1013. if ip != nil {
  1014. for _, bwLimit := range u.Filters.BandwidthLimits {
  1015. for _, source := range bwLimit.Sources {
  1016. _, ipNet, err := net.ParseCIDR(source)
  1017. if err == nil {
  1018. if ipNet.Contains(ip) {
  1019. logger.Debug(logSender, connectionID, "override bandwidth limit for ip %#v, upload limit: %v KB/s, download limit: %v KB/s",
  1020. clientIP, bwLimit.UploadBandwidth, bwLimit.DownloadBandwidth)
  1021. return bwLimit.UploadBandwidth, bwLimit.DownloadBandwidth
  1022. }
  1023. }
  1024. }
  1025. }
  1026. }
  1027. }
  1028. return u.UploadBandwidth, u.DownloadBandwidth
  1029. }
  1030. // IsLoginFromAddrAllowed returns true if the login is allowed from the specified remoteAddr.
  1031. // If AllowedIP is defined only the specified IP/Mask can login.
  1032. // If DeniedIP is defined the specified IP/Mask cannot login.
  1033. // If an IP is both allowed and denied then login will be denied
  1034. func (u *User) IsLoginFromAddrAllowed(remoteAddr string) bool {
  1035. if len(u.Filters.AllowedIP) == 0 && len(u.Filters.DeniedIP) == 0 {
  1036. return true
  1037. }
  1038. remoteIP := net.ParseIP(util.GetIPFromRemoteAddress(remoteAddr))
  1039. // if remoteIP is invalid we allow login, this should never happen
  1040. if remoteIP == nil {
  1041. logger.Warn(logSender, "", "login allowed for invalid IP. remote address: %#v", remoteAddr)
  1042. return true
  1043. }
  1044. for _, IPMask := range u.Filters.DeniedIP {
  1045. _, IPNet, err := net.ParseCIDR(IPMask)
  1046. if err != nil {
  1047. return false
  1048. }
  1049. if IPNet.Contains(remoteIP) {
  1050. return false
  1051. }
  1052. }
  1053. for _, IPMask := range u.Filters.AllowedIP {
  1054. _, IPNet, err := net.ParseCIDR(IPMask)
  1055. if err != nil {
  1056. return false
  1057. }
  1058. if IPNet.Contains(remoteIP) {
  1059. return true
  1060. }
  1061. }
  1062. return len(u.Filters.AllowedIP) == 0
  1063. }
  1064. // GetPermissionsAsJSON returns the permissions as json byte array
  1065. func (u *User) GetPermissionsAsJSON() ([]byte, error) {
  1066. return json.Marshal(u.Permissions)
  1067. }
  1068. // GetPublicKeysAsJSON returns the public keys as json byte array
  1069. func (u *User) GetPublicKeysAsJSON() ([]byte, error) {
  1070. return json.Marshal(u.PublicKeys)
  1071. }
  1072. // GetFiltersAsJSON returns the filters as json byte array
  1073. func (u *User) GetFiltersAsJSON() ([]byte, error) {
  1074. return json.Marshal(u.Filters)
  1075. }
  1076. // GetFsConfigAsJSON returns the filesystem config as json byte array
  1077. func (u *User) GetFsConfigAsJSON() ([]byte, error) {
  1078. return json.Marshal(u.FsConfig)
  1079. }
  1080. // GetUID returns a validate uid, suitable for use with os.Chown
  1081. func (u *User) GetUID() int {
  1082. if u.UID <= 0 || u.UID > math.MaxInt32 {
  1083. return -1
  1084. }
  1085. return u.UID
  1086. }
  1087. // GetGID returns a validate gid, suitable for use with os.Chown
  1088. func (u *User) GetGID() int {
  1089. if u.GID <= 0 || u.GID > math.MaxInt32 {
  1090. return -1
  1091. }
  1092. return u.GID
  1093. }
  1094. // GetHomeDir returns the shortest path name equivalent to the user's home directory
  1095. func (u *User) GetHomeDir() string {
  1096. return u.HomeDir
  1097. }
  1098. // HasRecentActivity returns true if the last user login is recent and so we can skip some expensive checks
  1099. func (u *User) HasRecentActivity() bool {
  1100. return isLastActivityRecent(u.LastLogin, lastLoginMinDelay)
  1101. }
  1102. // HasQuotaRestrictions returns true if there are any disk quota restrictions
  1103. func (u *User) HasQuotaRestrictions() bool {
  1104. return u.QuotaFiles > 0 || u.QuotaSize > 0
  1105. }
  1106. // HasTransferQuotaRestrictions returns true if there are any data transfer restrictions
  1107. func (u *User) HasTransferQuotaRestrictions() bool {
  1108. if len(u.Filters.DataTransferLimits) > 0 {
  1109. return true
  1110. }
  1111. return u.UploadDataTransfer > 0 || u.TotalDataTransfer > 0 || u.DownloadDataTransfer > 0
  1112. }
  1113. // GetDataTransferLimits returns upload, download and total data transfer limits
  1114. func (u *User) GetDataTransferLimits(clientIP string) (int64, int64, int64) {
  1115. var total, ul, dl int64
  1116. if len(u.Filters.DataTransferLimits) > 0 {
  1117. ip := net.ParseIP(clientIP)
  1118. if ip != nil {
  1119. for _, limit := range u.Filters.DataTransferLimits {
  1120. for _, source := range limit.Sources {
  1121. _, ipNet, err := net.ParseCIDR(source)
  1122. if err == nil {
  1123. if ipNet.Contains(ip) {
  1124. if limit.TotalDataTransfer > 0 {
  1125. total = limit.TotalDataTransfer * 1048576
  1126. }
  1127. if limit.DownloadDataTransfer > 0 {
  1128. dl = limit.DownloadDataTransfer * 1048576
  1129. }
  1130. if limit.UploadDataTransfer > 0 {
  1131. ul = limit.UploadDataTransfer * 1048576
  1132. }
  1133. return ul, dl, total
  1134. }
  1135. }
  1136. }
  1137. }
  1138. }
  1139. }
  1140. if u.TotalDataTransfer > 0 {
  1141. total = u.TotalDataTransfer * 1048576
  1142. }
  1143. if u.DownloadDataTransfer > 0 {
  1144. dl = u.DownloadDataTransfer * 1048576
  1145. }
  1146. if u.UploadDataTransfer > 0 {
  1147. ul = u.UploadDataTransfer * 1048576
  1148. }
  1149. return ul, dl, total
  1150. }
  1151. // GetQuotaSummary returns used quota and limits if defined
  1152. func (u *User) GetQuotaSummary() string {
  1153. var sb strings.Builder
  1154. addSection := func() {
  1155. if sb.Len() > 0 {
  1156. sb.WriteString(". ")
  1157. }
  1158. }
  1159. if u.UsedQuotaFiles > 0 || u.QuotaFiles > 0 {
  1160. sb.WriteString(fmt.Sprintf("Files: %v", u.UsedQuotaFiles))
  1161. if u.QuotaFiles > 0 {
  1162. sb.WriteString(fmt.Sprintf("/%v", u.QuotaFiles))
  1163. }
  1164. }
  1165. if u.UsedQuotaSize > 0 || u.QuotaSize > 0 {
  1166. addSection()
  1167. sb.WriteString(fmt.Sprintf("Size: %v", util.ByteCountIEC(u.UsedQuotaSize)))
  1168. if u.QuotaSize > 0 {
  1169. sb.WriteString(fmt.Sprintf("/%v", util.ByteCountIEC(u.QuotaSize)))
  1170. }
  1171. }
  1172. if u.TotalDataTransfer > 0 {
  1173. addSection()
  1174. total := u.UsedDownloadDataTransfer + u.UsedUploadDataTransfer
  1175. sb.WriteString(fmt.Sprintf("Transfer: %v/%v", util.ByteCountIEC(total),
  1176. util.ByteCountIEC(u.TotalDataTransfer*1048576)))
  1177. }
  1178. if u.UploadDataTransfer > 0 {
  1179. addSection()
  1180. sb.WriteString(fmt.Sprintf("UL: %v/%v", util.ByteCountIEC(u.UsedUploadDataTransfer),
  1181. util.ByteCountIEC(u.UploadDataTransfer*1048576)))
  1182. }
  1183. if u.DownloadDataTransfer > 0 {
  1184. addSection()
  1185. sb.WriteString(fmt.Sprintf("DL: %v/%v", util.ByteCountIEC(u.UsedDownloadDataTransfer),
  1186. util.ByteCountIEC(u.DownloadDataTransfer*1048576)))
  1187. }
  1188. return sb.String()
  1189. }
  1190. // GetPermissionsAsString returns the user's permissions as comma separated string
  1191. func (u *User) GetPermissionsAsString() string {
  1192. result := ""
  1193. for dir, perms := range u.Permissions {
  1194. dirPerms := strings.Join(perms, ", ")
  1195. dp := fmt.Sprintf("%#v: %#v", dir, dirPerms)
  1196. if dir == "/" {
  1197. if result != "" {
  1198. result = dp + ", " + result
  1199. } else {
  1200. result = dp
  1201. }
  1202. } else {
  1203. if result != "" {
  1204. result += ", "
  1205. }
  1206. result += dp
  1207. }
  1208. }
  1209. return result
  1210. }
  1211. // GetBandwidthAsString returns bandwidth limits if defines
  1212. func (u *User) GetBandwidthAsString() string {
  1213. var sb strings.Builder
  1214. sb.WriteString("DL: ")
  1215. if u.DownloadBandwidth > 0 {
  1216. sb.WriteString(util.ByteCountIEC(u.DownloadBandwidth*1000) + "/s.")
  1217. } else {
  1218. sb.WriteString("unlimited.")
  1219. }
  1220. sb.WriteString(" UL: ")
  1221. if u.UploadBandwidth > 0 {
  1222. sb.WriteString(util.ByteCountIEC(u.UploadBandwidth*1000) + "/s.")
  1223. } else {
  1224. sb.WriteString("unlimited.")
  1225. }
  1226. return sb.String()
  1227. }
  1228. // GetMFAStatusAsString returns MFA status
  1229. func (u *User) GetMFAStatusAsString() string {
  1230. if u.Filters.TOTPConfig.Enabled {
  1231. return strings.Join(u.Filters.TOTPConfig.Protocols, ", ")
  1232. }
  1233. return "Disabled"
  1234. }
  1235. // GetLastLoginAsString returns the last login as string
  1236. func (u *User) GetLastLoginAsString() string {
  1237. if u.LastLogin > 0 {
  1238. return util.GetTimeFromMsecSinceEpoch(u.LastLogin).UTC().Format(iso8601UTCFormat)
  1239. }
  1240. return ""
  1241. }
  1242. // GetLastQuotaUpdateAsString returns the last quota update as string
  1243. func (u *User) GetLastQuotaUpdateAsString() string {
  1244. if u.LastQuotaUpdate > 0 {
  1245. return util.GetTimeFromMsecSinceEpoch(u.LastQuotaUpdate).UTC().Format(iso8601UTCFormat)
  1246. }
  1247. return ""
  1248. }
  1249. // GetStorageDescrition returns the storage description
  1250. func (u *User) GetStorageDescrition() string {
  1251. switch u.FsConfig.Provider {
  1252. case sdk.LocalFilesystemProvider:
  1253. return fmt.Sprintf("Local: %v", u.GetHomeDir())
  1254. case sdk.S3FilesystemProvider:
  1255. return fmt.Sprintf("S3: %v", u.FsConfig.S3Config.Bucket)
  1256. case sdk.GCSFilesystemProvider:
  1257. return fmt.Sprintf("GCS: %v", u.FsConfig.GCSConfig.Bucket)
  1258. case sdk.AzureBlobFilesystemProvider:
  1259. return fmt.Sprintf("AzBlob: %v", u.FsConfig.AzBlobConfig.Container)
  1260. case sdk.CryptedFilesystemProvider:
  1261. return fmt.Sprintf("Encrypted: %v", u.GetHomeDir())
  1262. case sdk.SFTPFilesystemProvider:
  1263. return fmt.Sprintf("SFTP: %v", u.FsConfig.SFTPConfig.Endpoint)
  1264. case sdk.HTTPFilesystemProvider:
  1265. return fmt.Sprintf("HTTP: %v", u.FsConfig.HTTPConfig.Endpoint)
  1266. default:
  1267. return ""
  1268. }
  1269. }
  1270. // GetGroupsAsString returns the user's groups as a string
  1271. func (u *User) GetGroupsAsString() string {
  1272. if len(u.Groups) == 0 {
  1273. return ""
  1274. }
  1275. var groups []string
  1276. for _, g := range u.Groups {
  1277. if g.Type == sdk.GroupTypePrimary {
  1278. groups = append(groups, "")
  1279. copy(groups[1:], groups)
  1280. groups[0] = g.Name
  1281. } else {
  1282. groups = append(groups, g.Name)
  1283. }
  1284. }
  1285. return strings.Join(groups, ",")
  1286. }
  1287. // GetInfoString returns user's info as string.
  1288. // Storage provider, number of public keys, max sessions, uid,
  1289. // gid, denied and allowed IP/Mask are returned
  1290. func (u *User) GetInfoString() string {
  1291. var result strings.Builder
  1292. if len(u.PublicKeys) > 0 {
  1293. result.WriteString(fmt.Sprintf("Public keys: %v. ", len(u.PublicKeys)))
  1294. }
  1295. if u.MaxSessions > 0 {
  1296. result.WriteString(fmt.Sprintf("Max sessions: %v. ", u.MaxSessions))
  1297. }
  1298. if u.UID > 0 {
  1299. result.WriteString(fmt.Sprintf("UID: %v. ", u.UID))
  1300. }
  1301. if u.GID > 0 {
  1302. result.WriteString(fmt.Sprintf("GID: %v. ", u.GID))
  1303. }
  1304. if len(u.Filters.DeniedLoginMethods) > 0 {
  1305. result.WriteString(fmt.Sprintf("Denied login methods: %v. ", strings.Join(u.Filters.DeniedLoginMethods, ",")))
  1306. }
  1307. if len(u.Filters.DeniedProtocols) > 0 {
  1308. result.WriteString(fmt.Sprintf("Denied protocols: %v. ", strings.Join(u.Filters.DeniedProtocols, ",")))
  1309. }
  1310. if len(u.Filters.DeniedIP) > 0 {
  1311. result.WriteString(fmt.Sprintf("Denied IP/Mask: %v. ", len(u.Filters.DeniedIP)))
  1312. }
  1313. if len(u.Filters.AllowedIP) > 0 {
  1314. result.WriteString(fmt.Sprintf("Allowed IP/Mask: %v", len(u.Filters.AllowedIP)))
  1315. }
  1316. return result.String()
  1317. }
  1318. // GetStatusAsString returns the user status as a string
  1319. func (u *User) GetStatusAsString() string {
  1320. if u.ExpirationDate > 0 && u.ExpirationDate < util.GetTimeAsMsSinceEpoch(time.Now()) {
  1321. return "Expired"
  1322. }
  1323. if u.Status == 1 {
  1324. return "Active"
  1325. }
  1326. return "Inactive"
  1327. }
  1328. // GetExpirationDateAsString returns expiration date formatted as YYYY-MM-DD
  1329. func (u *User) GetExpirationDateAsString() string {
  1330. if u.ExpirationDate > 0 {
  1331. t := util.GetTimeFromMsecSinceEpoch(u.ExpirationDate)
  1332. return t.Format("2006-01-02")
  1333. }
  1334. return ""
  1335. }
  1336. // GetAllowedIPAsString returns the allowed IP as comma separated string
  1337. func (u *User) GetAllowedIPAsString() string {
  1338. return strings.Join(u.Filters.AllowedIP, ",")
  1339. }
  1340. // GetDeniedIPAsString returns the denied IP as comma separated string
  1341. func (u *User) GetDeniedIPAsString() string {
  1342. return strings.Join(u.Filters.DeniedIP, ",")
  1343. }
  1344. // HasExternalAuth returns true if the external authentication is globally enabled
  1345. // and it is not disabled for this user
  1346. func (u *User) HasExternalAuth() bool {
  1347. if u.Filters.Hooks.ExternalAuthDisabled {
  1348. return false
  1349. }
  1350. if config.ExternalAuthHook != "" {
  1351. return true
  1352. }
  1353. return plugin.Handler.HasAuthenticators()
  1354. }
  1355. // CountUnusedRecoveryCodes returns the number of unused recovery codes
  1356. func (u *User) CountUnusedRecoveryCodes() int {
  1357. unused := 0
  1358. for _, code := range u.Filters.RecoveryCodes {
  1359. if !code.Used {
  1360. unused++
  1361. }
  1362. }
  1363. return unused
  1364. }
  1365. // SetEmptySecretsIfNil sets the secrets to empty if nil
  1366. func (u *User) SetEmptySecretsIfNil() {
  1367. u.FsConfig.SetEmptySecretsIfNil()
  1368. for idx := range u.VirtualFolders {
  1369. vfolder := &u.VirtualFolders[idx]
  1370. vfolder.FsConfig.SetEmptySecretsIfNil()
  1371. }
  1372. if u.Filters.TOTPConfig.Secret == nil {
  1373. u.Filters.TOTPConfig.Secret = kms.NewEmptySecret()
  1374. }
  1375. }
  1376. func (u *User) hasMainDataTransferLimits() bool {
  1377. return u.UploadDataTransfer > 0 || u.DownloadDataTransfer > 0 || u.TotalDataTransfer > 0
  1378. }
  1379. // HasPrimaryGroup returns true if the user has the specified primary group
  1380. func (u *User) HasPrimaryGroup(name string) bool {
  1381. for _, g := range u.Groups {
  1382. if g.Name == name {
  1383. return g.Type == sdk.GroupTypePrimary
  1384. }
  1385. }
  1386. return false
  1387. }
  1388. // HasSecondaryGroup returns true if the user has the specified secondary group
  1389. func (u *User) HasSecondaryGroup(name string) bool {
  1390. for _, g := range u.Groups {
  1391. if g.Name == name {
  1392. return g.Type == sdk.GroupTypeSecondary
  1393. }
  1394. }
  1395. return false
  1396. }
  1397. func (u *User) applyGroupSettings(groupsMapping map[string]Group) {
  1398. if len(u.Groups) == 0 {
  1399. return
  1400. }
  1401. if u.groupSettingsApplied {
  1402. return
  1403. }
  1404. for _, g := range u.Groups {
  1405. if g.Type == sdk.GroupTypePrimary {
  1406. if group, ok := groupsMapping[g.Name]; ok {
  1407. u.mergeWithPrimaryGroup(group)
  1408. } else {
  1409. providerLog(logger.LevelError, "mapping not found for user %s, group %s", u.Username, g.Name)
  1410. }
  1411. break
  1412. }
  1413. }
  1414. for _, g := range u.Groups {
  1415. if g.Type == sdk.GroupTypeSecondary {
  1416. if group, ok := groupsMapping[g.Name]; ok {
  1417. u.mergeAdditiveProperties(group, sdk.GroupTypeSecondary)
  1418. } else {
  1419. providerLog(logger.LevelError, "mapping not found for user %s, group %s", u.Username, g.Name)
  1420. }
  1421. }
  1422. }
  1423. u.removeDuplicatesAfterGroupMerge()
  1424. }
  1425. // LoadAndApplyGroupSettings update the user by loading and applying the group settings
  1426. func (u *User) LoadAndApplyGroupSettings() error {
  1427. if len(u.Groups) == 0 {
  1428. return nil
  1429. }
  1430. if u.groupSettingsApplied {
  1431. return nil
  1432. }
  1433. names := make([]string, 0, len(u.Groups))
  1434. var primaryGroupName string
  1435. for _, g := range u.Groups {
  1436. if g.Type == sdk.GroupTypePrimary {
  1437. primaryGroupName = g.Name
  1438. }
  1439. names = append(names, g.Name)
  1440. }
  1441. groups, err := provider.getGroupsWithNames(names)
  1442. if err != nil {
  1443. return fmt.Errorf("unable to get groups: %w", err)
  1444. }
  1445. // make sure to always merge with the primary group first
  1446. for idx, g := range groups {
  1447. if g.Name == primaryGroupName {
  1448. u.mergeWithPrimaryGroup(g)
  1449. lastIdx := len(groups) - 1
  1450. groups[idx] = groups[lastIdx]
  1451. groups = groups[:lastIdx]
  1452. break
  1453. }
  1454. }
  1455. for _, g := range groups {
  1456. u.mergeAdditiveProperties(g, sdk.GroupTypeSecondary)
  1457. }
  1458. u.removeDuplicatesAfterGroupMerge()
  1459. return nil
  1460. }
  1461. func (u *User) replacePlaceholder(value string) string {
  1462. if value == "" {
  1463. return value
  1464. }
  1465. return strings.ReplaceAll(value, "%username%", u.Username)
  1466. }
  1467. func (u *User) replaceFsConfigPlaceholders(fsConfig vfs.Filesystem) vfs.Filesystem {
  1468. switch fsConfig.Provider {
  1469. case sdk.S3FilesystemProvider:
  1470. fsConfig.S3Config.KeyPrefix = u.replacePlaceholder(fsConfig.S3Config.KeyPrefix)
  1471. case sdk.GCSFilesystemProvider:
  1472. fsConfig.GCSConfig.KeyPrefix = u.replacePlaceholder(fsConfig.GCSConfig.KeyPrefix)
  1473. case sdk.AzureBlobFilesystemProvider:
  1474. fsConfig.AzBlobConfig.KeyPrefix = u.replacePlaceholder(fsConfig.AzBlobConfig.KeyPrefix)
  1475. case sdk.SFTPFilesystemProvider:
  1476. fsConfig.SFTPConfig.Username = u.replacePlaceholder(fsConfig.SFTPConfig.Username)
  1477. fsConfig.SFTPConfig.Prefix = u.replacePlaceholder(fsConfig.SFTPConfig.Prefix)
  1478. case sdk.HTTPFilesystemProvider:
  1479. fsConfig.HTTPConfig.Username = u.replacePlaceholder(fsConfig.HTTPConfig.Username)
  1480. }
  1481. return fsConfig
  1482. }
  1483. func (u *User) mergeWithPrimaryGroup(group Group) {
  1484. if group.UserSettings.HomeDir != "" {
  1485. u.HomeDir = u.replacePlaceholder(group.UserSettings.HomeDir)
  1486. }
  1487. if group.UserSettings.FsConfig.Provider != 0 {
  1488. u.FsConfig = u.replaceFsConfigPlaceholders(group.UserSettings.FsConfig)
  1489. }
  1490. if u.MaxSessions == 0 {
  1491. u.MaxSessions = group.UserSettings.MaxSessions
  1492. }
  1493. if u.QuotaSize == 0 {
  1494. u.QuotaSize = group.UserSettings.QuotaSize
  1495. }
  1496. if u.QuotaFiles == 0 {
  1497. u.QuotaFiles = group.UserSettings.QuotaFiles
  1498. }
  1499. if u.UploadBandwidth == 0 {
  1500. u.UploadBandwidth = group.UserSettings.UploadBandwidth
  1501. }
  1502. if u.DownloadBandwidth == 0 {
  1503. u.DownloadBandwidth = group.UserSettings.DownloadBandwidth
  1504. }
  1505. if !u.hasMainDataTransferLimits() {
  1506. u.UploadDataTransfer = group.UserSettings.UploadDataTransfer
  1507. u.DownloadDataTransfer = group.UserSettings.DownloadDataTransfer
  1508. u.TotalDataTransfer = group.UserSettings.TotalDataTransfer
  1509. }
  1510. u.mergePrimaryGroupFilters(group.UserSettings.Filters)
  1511. u.mergeAdditiveProperties(group, sdk.GroupTypePrimary)
  1512. }
  1513. func (u *User) mergePrimaryGroupFilters(filters sdk.BaseUserFilters) {
  1514. if u.Filters.MaxUploadFileSize == 0 {
  1515. u.Filters.MaxUploadFileSize = filters.MaxUploadFileSize
  1516. }
  1517. if u.Filters.TLSUsername == "" || u.Filters.TLSUsername == sdk.TLSUsernameNone {
  1518. u.Filters.TLSUsername = filters.TLSUsername
  1519. }
  1520. if !u.Filters.Hooks.CheckPasswordDisabled {
  1521. u.Filters.Hooks.CheckPasswordDisabled = filters.Hooks.CheckPasswordDisabled
  1522. }
  1523. if !u.Filters.Hooks.PreLoginDisabled {
  1524. u.Filters.Hooks.PreLoginDisabled = filters.Hooks.PreLoginDisabled
  1525. }
  1526. if !u.Filters.Hooks.ExternalAuthDisabled {
  1527. u.Filters.Hooks.ExternalAuthDisabled = filters.Hooks.ExternalAuthDisabled
  1528. }
  1529. if !u.Filters.DisableFsChecks {
  1530. u.Filters.DisableFsChecks = filters.DisableFsChecks
  1531. }
  1532. if !u.Filters.AllowAPIKeyAuth {
  1533. u.Filters.AllowAPIKeyAuth = filters.AllowAPIKeyAuth
  1534. }
  1535. if u.Filters.ExternalAuthCacheTime == 0 {
  1536. u.Filters.ExternalAuthCacheTime = filters.ExternalAuthCacheTime
  1537. }
  1538. if u.Filters.StartDirectory == "" {
  1539. u.Filters.StartDirectory = u.replacePlaceholder(filters.StartDirectory)
  1540. }
  1541. }
  1542. func (u *User) mergeAdditiveProperties(group Group, groupType int) {
  1543. u.mergeVirtualFolders(group, groupType)
  1544. u.mergePermissions(group, groupType)
  1545. u.mergeFilePatterns(group, groupType)
  1546. u.Filters.BandwidthLimits = append(u.Filters.BandwidthLimits, group.UserSettings.Filters.BandwidthLimits...)
  1547. u.Filters.DataTransferLimits = append(u.Filters.DataTransferLimits, group.UserSettings.Filters.DataTransferLimits...)
  1548. u.Filters.AllowedIP = append(u.Filters.AllowedIP, group.UserSettings.Filters.AllowedIP...)
  1549. u.Filters.DeniedIP = append(u.Filters.DeniedIP, group.UserSettings.Filters.DeniedIP...)
  1550. u.Filters.DeniedLoginMethods = append(u.Filters.DeniedLoginMethods, group.UserSettings.Filters.DeniedLoginMethods...)
  1551. u.Filters.DeniedProtocols = append(u.Filters.DeniedProtocols, group.UserSettings.Filters.DeniedProtocols...)
  1552. u.Filters.WebClient = append(u.Filters.WebClient, group.UserSettings.Filters.WebClient...)
  1553. u.Filters.TwoFactorAuthProtocols = append(u.Filters.TwoFactorAuthProtocols, group.UserSettings.Filters.TwoFactorAuthProtocols...)
  1554. }
  1555. func (u *User) mergeVirtualFolders(group Group, groupType int) {
  1556. if len(group.VirtualFolders) > 0 {
  1557. folderPaths := make(map[string]bool)
  1558. for _, folder := range u.VirtualFolders {
  1559. folderPaths[folder.VirtualPath] = true
  1560. }
  1561. for _, folder := range group.VirtualFolders {
  1562. if folder.VirtualPath == "/" && groupType != sdk.GroupTypePrimary {
  1563. continue
  1564. }
  1565. folder.VirtualPath = u.replacePlaceholder(folder.VirtualPath)
  1566. if _, ok := folderPaths[folder.VirtualPath]; !ok {
  1567. folder.MappedPath = u.replacePlaceholder(folder.MappedPath)
  1568. folder.FsConfig = u.replaceFsConfigPlaceholders(folder.FsConfig)
  1569. u.VirtualFolders = append(u.VirtualFolders, folder)
  1570. }
  1571. }
  1572. }
  1573. }
  1574. func (u *User) mergePermissions(group Group, groupType int) {
  1575. for k, v := range group.UserSettings.Permissions {
  1576. if k == "/" {
  1577. if groupType == sdk.GroupTypePrimary {
  1578. u.Permissions[k] = v
  1579. } else {
  1580. continue
  1581. }
  1582. }
  1583. k = u.replacePlaceholder(k)
  1584. if _, ok := u.Permissions[k]; !ok {
  1585. u.Permissions[k] = v
  1586. }
  1587. }
  1588. }
  1589. func (u *User) mergeFilePatterns(group Group, groupType int) {
  1590. if len(group.UserSettings.Filters.FilePatterns) > 0 {
  1591. patternPaths := make(map[string]bool)
  1592. for _, pattern := range u.Filters.FilePatterns {
  1593. patternPaths[pattern.Path] = true
  1594. }
  1595. for _, pattern := range group.UserSettings.Filters.FilePatterns {
  1596. if pattern.Path == "/" && groupType != sdk.GroupTypePrimary {
  1597. continue
  1598. }
  1599. pattern.Path = u.replacePlaceholder(pattern.Path)
  1600. if _, ok := patternPaths[pattern.Path]; !ok {
  1601. u.Filters.FilePatterns = append(u.Filters.FilePatterns, pattern)
  1602. }
  1603. }
  1604. }
  1605. }
  1606. func (u *User) removeDuplicatesAfterGroupMerge() {
  1607. u.Filters.AllowedIP = util.RemoveDuplicates(u.Filters.AllowedIP, false)
  1608. u.Filters.DeniedIP = util.RemoveDuplicates(u.Filters.DeniedIP, false)
  1609. u.Filters.DeniedLoginMethods = util.RemoveDuplicates(u.Filters.DeniedLoginMethods, false)
  1610. u.Filters.DeniedProtocols = util.RemoveDuplicates(u.Filters.DeniedProtocols, false)
  1611. u.Filters.WebClient = util.RemoveDuplicates(u.Filters.WebClient, false)
  1612. u.Filters.TwoFactorAuthProtocols = util.RemoveDuplicates(u.Filters.TwoFactorAuthProtocols, false)
  1613. u.SetEmptySecretsIfNil()
  1614. u.groupSettingsApplied = true
  1615. }
  1616. func (u *User) getACopy() User {
  1617. u.SetEmptySecretsIfNil()
  1618. pubKeys := make([]string, len(u.PublicKeys))
  1619. copy(pubKeys, u.PublicKeys)
  1620. virtualFolders := make([]vfs.VirtualFolder, 0, len(u.VirtualFolders))
  1621. for idx := range u.VirtualFolders {
  1622. vfolder := u.VirtualFolders[idx].GetACopy()
  1623. virtualFolders = append(virtualFolders, vfolder)
  1624. }
  1625. groups := make([]sdk.GroupMapping, 0, len(u.Groups))
  1626. for _, g := range u.Groups {
  1627. groups = append(groups, sdk.GroupMapping{
  1628. Name: g.Name,
  1629. Type: g.Type,
  1630. })
  1631. }
  1632. permissions := make(map[string][]string)
  1633. for k, v := range u.Permissions {
  1634. perms := make([]string, len(v))
  1635. copy(perms, v)
  1636. permissions[k] = perms
  1637. }
  1638. filters := UserFilters{
  1639. BaseUserFilters: copyBaseUserFilters(u.Filters.BaseUserFilters),
  1640. }
  1641. filters.TOTPConfig.Enabled = u.Filters.TOTPConfig.Enabled
  1642. filters.TOTPConfig.ConfigName = u.Filters.TOTPConfig.ConfigName
  1643. filters.TOTPConfig.Secret = u.Filters.TOTPConfig.Secret.Clone()
  1644. filters.TOTPConfig.Protocols = make([]string, len(u.Filters.TOTPConfig.Protocols))
  1645. copy(filters.TOTPConfig.Protocols, u.Filters.TOTPConfig.Protocols)
  1646. filters.RecoveryCodes = make([]RecoveryCode, 0, len(u.Filters.RecoveryCodes))
  1647. for _, code := range u.Filters.RecoveryCodes {
  1648. if code.Secret == nil {
  1649. code.Secret = kms.NewEmptySecret()
  1650. }
  1651. filters.RecoveryCodes = append(filters.RecoveryCodes, RecoveryCode{
  1652. Secret: code.Secret.Clone(),
  1653. Used: code.Used,
  1654. })
  1655. }
  1656. return User{
  1657. BaseUser: sdk.BaseUser{
  1658. ID: u.ID,
  1659. Username: u.Username,
  1660. Email: u.Email,
  1661. Password: u.Password,
  1662. PublicKeys: pubKeys,
  1663. HomeDir: u.HomeDir,
  1664. UID: u.UID,
  1665. GID: u.GID,
  1666. MaxSessions: u.MaxSessions,
  1667. QuotaSize: u.QuotaSize,
  1668. QuotaFiles: u.QuotaFiles,
  1669. Permissions: permissions,
  1670. UsedQuotaSize: u.UsedQuotaSize,
  1671. UsedQuotaFiles: u.UsedQuotaFiles,
  1672. LastQuotaUpdate: u.LastQuotaUpdate,
  1673. UploadBandwidth: u.UploadBandwidth,
  1674. DownloadBandwidth: u.DownloadBandwidth,
  1675. UploadDataTransfer: u.UploadDataTransfer,
  1676. DownloadDataTransfer: u.DownloadDataTransfer,
  1677. TotalDataTransfer: u.TotalDataTransfer,
  1678. UsedUploadDataTransfer: u.UsedUploadDataTransfer,
  1679. UsedDownloadDataTransfer: u.UsedDownloadDataTransfer,
  1680. Status: u.Status,
  1681. ExpirationDate: u.ExpirationDate,
  1682. LastLogin: u.LastLogin,
  1683. AdditionalInfo: u.AdditionalInfo,
  1684. Description: u.Description,
  1685. CreatedAt: u.CreatedAt,
  1686. UpdatedAt: u.UpdatedAt,
  1687. },
  1688. Filters: filters,
  1689. VirtualFolders: virtualFolders,
  1690. Groups: groups,
  1691. FsConfig: u.FsConfig.GetACopy(),
  1692. groupSettingsApplied: u.groupSettingsApplied,
  1693. }
  1694. }
  1695. // GetEncryptionAdditionalData returns the additional data to use for AEAD
  1696. func (u *User) GetEncryptionAdditionalData() string {
  1697. return u.Username
  1698. }
  1699. // GetGCSCredentialsFilePath returns the path for GCS credentials
  1700. func (u *User) GetGCSCredentialsFilePath() string {
  1701. return filepath.Join(credentialsDirPath, fmt.Sprintf("%v_gcs_credentials.json", u.Username))
  1702. }