user.go 61 KB

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