user.go 57 KB

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