user.go 58 KB

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