user.go 61 KB

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