user.go 58 KB

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